MVC 3布局页面,剃刀模板,DROPDOWNLIST [英] MVC 3 Layout Page, Razor Template, and DropdownList

查看:97
本文介绍了MVC 3布局页面,剃刀模板,DROPDOWNLIST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包括在我的网站的所有网页下降的几年下拉列表中。我认为一个好地方,把这个逻辑是在布局页(_layout.cshtml)。如果用户更改了一年,我想改变我的年度会议(ModelBinder的)来改变。这是很容易与ASP.NET Web表单的事,但似乎几乎不可能在MVC做。我试过,没有运气的局部视图。任何人有任何想法?

I want to include a drop down list of years across all the pages in my website. I assumed a good place to put this logic was in the layout page (_layout.cshtml). If a user changes the year I want to change my year session (ModelBinder) to change as well. This was so easy to do with ASP.NET web forms, but seems near impossible to do in MVC. I tried a partial view with no luck. Anybody have any ideas?

推荐答案

像往常一样,你可以通过定义视图模型启动:

As usual you could start by defining a view model:

public class YearsViewModel
{
    public string Year { get; set; }
    public IEnumerable<SelectListItem> Years
    {
        get
        {
            return new SelectList(
                Enumerable.Range(1900, 112)
                .OrderByDescending(year => year)
                .Select(year => new SelectListItem
                {
                    Value = year.ToString(),
                    Text = year.ToString()
                }
            ), "Value", "Text");
        }
    }
}

然后,控制器:

public class YearsController : Controller
{
    public ActionResult Index()
    {
        return View(new YearsViewModel());
    }

    [HttpPost]
    public ActionResult Index(int year)
    {
        // TODO: do something with the selected year
        return new EmptyResult();
    }
}

和为索引动作对应的视图:

and a corresponding view for the index action:

@model SomeAppName.Models.YearsViewModel
@{
    Layout = null;
}
@Html.DropDownListFor(x => x.Year, Model.Years)

最后你里面 _Layout.cshtml 您可以使用此控制器:

<div id="selectyear">@Html.Action("index", "years")</div>

和重视这将发送一个AJAX请求相应的脚本时,值的变化:

and attach a corresponding script which would send an AJAX request when the value changes:

$(function () {
    $('#selectyear select').change(function () {
        $.post('@Url.Action("index", "years")', { year: $(this).val() }, function (result) {

        });
    });
});

这篇关于MVC 3布局页面,剃刀模板,DROPDOWNLIST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆