2012-08-09 23 views
0

我有一個html.dropdownlist正在填充索引操作。MVC 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); 
    } 

我需要做什麼才能使下拉列表在顯示後列出的選定值而不是列表中的第一個值?

回答

0

我想通了。我需要將Html.DropdownList命名爲Years以外的其他名稱,例如ddlYears