2012-01-18 149 views
0

我有一個下拉列表,當它的選定的值被改變時重新加載頁面。這工作並按預期呈現。唯一的問題是下拉列表會回到默認值。如何更改默認值以匹配ViewBag.Value?基於viewbag設置默認的下拉默認值

@Html.DropDownListFor(model => model.LevelId, 
          (
           from choice in 
            (from p in Model.Defaults 
            group p by new { p.LevelId, p.LevelDescription } into c 
            select new { c.Key.LevelId, c.Key.LevelDescription }) 
           select new SelectListItem 
              { 
               Text = choice.LevelDescription, 
               Value = choice.LevelId.ToString(), 
               Selected = false 
              })) 

的JScript

$("#LevelId").change(function() { 

     var clientId = @Model.ClientId; 
     var compareDate = $("#EffectiveDate").val(); 
     var level = $(this).val(); 
     var params = $.param({ clientId: clientId, compareDate: compareDate, level : level }); 
     var link = '@Url.Action("Create", "Choices")'; //"\\Choices\\RefreshView"; 
     var url = link + "?" + params; 
     document.location = url; 
    }); 

控制器設置ViewBag.Level基於在

回答

1

通過帕拉姆您可以將屬性添加到您的視圖模型,這將是一個IEnumerable<SelectListItem>,你會像初始化在你的控制器中。然後,只需將LevelId屬性設置爲你想預選值:

public ActionResult Foo(string level) 
{ 
    var model = new MyViewModel(); 
    var values = from choice in 
     (from p in Model.Defaults 
     group p by new { p.LevelId, p.LevelDescription } into c 
     select new { c.Key.LevelId, c.Key.LevelDescription }) 
     select new { 
      Text = choice.LevelDescription, 
      Value = choice.LevelId.ToString() 
     } 
    ); 
    model.Items = new SelectList(values, "Text", "Value"); 
    model.LevelId = level; 
    return View(model); 
} 

,然後在您的視圖:

@Html.DropDownListFor(model => model.LevelId, Model.Items) 
+0

我得到這個錯誤的model.items =新的SelectList(值.. ..)錯誤不能將類型'System.Web.Mvc.SelectList'隱式轉換爲'System.Collections.Generic.IEnumerable '。 – 2012-01-18 18:16:02

+0

@atbyrd,你應該使用'IEnumerable '而不是'IEnumerable '。你似乎選擇了錯誤的'SelectListItem'類:-) – 2012-01-18 18:20:56

+0

嗯搞明白了。感謝您的幫助,現在它的工作非常棒! – 2012-01-18 18:24:02