2011-11-10 85 views
0

我對控制器側這個代碼初始化下拉Html.dropdownlist不保留所選擇的值

 List<SelectListItem> items = new List<SelectListItem>(); 
     items.Add(new SelectListItem 
     {Text = "All", 
     Value = "All" 

     }); 
     items.Add(new SelectListItem 
     { 
      Text = "val1", 
      Value = "val1" 
     }); 
     items.Add(new SelectListItem 
     { 
      Text = "val2", 
      Value = "val2" 
     }); 

     ViewData["DDLItems"] = items; 

     // I have added this code because I am passing the selection back to this  action 
     if (Activefilter == null){ Activefilter = "All" ;} 

     ViewData["Activefilter"] = Activefilter; 

在視圖,我有此代碼

<%= Html.DropDownList("ActiveFilter", (IEnumerable<SelectListItem>)ViewData["DDLItems"], new { onChange = "func(1)" })%> 

jQuery的,我這

$(document).ready(function() { 

         $('#Activefilter').val(<%= ViewData["Activefilter"].ToString() %>); 
      } 

所以,每當我改變下拉的值,行動被調用如上所示。的可視數據[「Actionfilter」]也需要在此行由用戶選擇的值,但是當控制回來視圖,

$('#Filter').val(<%= ViewData["Activefilter"].ToString() %>); 

,它說將值「全部」是未定義的。

每次頁面重新加載時,我都希望下拉菜單保留選定的值。你能幫忙嗎?

+0

使用cookie?或會話變量? – ManseUK

+0

你能舉個例子嗎?我如何實現它? – user1005310

回答

0

您可以使用一個SelectList()並在構造函數中傳遞選定的項目。而不是使用列表。 remeber selected

爲什麼不被採取在此實例中選擇的值,

 List<SelectListItem> items = new List<SelectListItem>(); 

     items.Add(new SelectListItem 
     { 
      Text = "All", 
      Value = "All" 

     }); 
     items.Add(new SelectListItem 
     { 
      Text = "val1", 
      Value = "val1", 
     }); 
     items.Add(new SelectListItem 
     { 
      Text = "val2", 
      Value = "val2"," 
     }); 


     string filter = "val1"; 
     ViewData["DDLItems1"] = new SelectList(items, "Text", "Value", filter); 
上視圖

,這裏是代碼

<div> @Html.DropDownList("FilterName", (SelectList)ViewData["DDLItems1"])</div> 

也就是說剃刀語法,切換到<%符號如果你不使用剃鬚刀

+0

user1005310我更改了我編輯過的解決方案的HTML部分 –