0

I have an html.dropdownlist that is being populated in the Index action.

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

I'm defining the html.dropdownlist so that changing the value will trigger a postback:

<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>

I'm capturing the postback and filtering the displayed table. I'm trying to have the dropdown list display the chosen value, but that is not working.

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

What do I need to do to have the dropdown list display the selected value after postback instead of the first value in the list?

4

1 回答 1

0

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

于 2012-08-10T00:21:47.580 回答