MVC html.dropdownlist在回发后显示选定的值

时间:2012-08-09 16:08:41

标签: asp.net-mvc postback retain html-select

我有一个在index操作中填充的html.dropdownlist。

    public ActionResult Index()
    {
        var maxyear = (from estiamte in dbBudget.Estimates
                       select estiamte.Year).Max();

        var years = (from estimate in dbBudget.Estimates
                     select new { estimate.Year }).Distinct().ToList();

        ViewData["Years"] = new SelectList(years.OrderByDescending(o => o.Year), "Year", "Year");

        var vu_Estimates = dbBudget.vu_Estimates.OrderByDescending(o => o.Expense).ThenBy(o => o.CategoryGroupSortOrder).ThenBy(o => o.SortOrder).Where(o => o.Year == maxyear).ToList();

        return View(vu_Estimates);
    }

我正在定义html.dropdownlist,以便更改该值将触发回发:

<div>
    <% using (Html.BeginForm()) { %>
        <%= Html.DropDownList("Years", (SelectList)ViewData["Years"], new { onchange = "this.form.submit();" })%> | <%: Html.ActionLink("Create New Year of Estimates", "CreateEstimates", "Estimate") %>
    <%} %>
</div>

我正在捕获回发并过滤显示的表格。我试图让下拉列表显示所选的值,但这不起作用。

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(FormCollection formCollection)
    {
        var years = (from estimate in dbBudget.Estimates
                     select new { estimate.Year }).Distinct().ToList();

        int year = Convert.ToInt32(formCollection["Years"]);

        ViewData["Years"] = new SelectList(years.OrderByDescending(o => o.Year), "Year", "Year", year);

        var vu_Estimates = dbBudget.vu_Estimates.OrderByDescending(o => o.Expense).ThenBy(o => o.CategoryGroupSortOrder).ThenBy(o => o.SortOrder).Where(o => o.Year == year).ToList();

        return View(vu_Estimates);
    }

如果让回传列表在回发后显示所选值而不是列表中的第一个值,我需要做什么?

1 个答案:

答案 0 :(得分:0)

我明白了。我需要将Html.DropdownList命名为Years以外的其他内容,例如ddlYears