【问题标题】:MVC html.dropdownlist display selected value after postbackMVC html.dropdownlist 在回发后显示选定的值
【发布时间】:2012-08-09 16:08:40
【问题描述】:

我有一个 html.dropdownlist 正在 Index 操作中填充。

    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);
    }

我需要做什么才能让下拉列表在回发后显示所选值而不是列表中的第一个值?

【问题讨论】:

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


    【解决方案1】:

    我想通了。我需要将Html.DropdownList 命名为Years 以外的名称,例如ddlYears.

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      相关资源
      最近更新 更多