對於MVC2/3來說,新的方法應該記住。另外,使用Ajax或jQuery不是一個選項。MVC3 - 訪問控制器中的下拉列表的內容
我有一個網頁,用戶必須從下拉列表中選擇一個項目,然後點擊「過濾器」按鈕。 (單擊此按鈕將簡單地觸發我的控制器中的默認POST動作,並返回經過篩選的結果列表。
我有一切工作,但我遇到了一個問題當篩選器操作完成並將控制權返回給我查看,下拉列表內容丟失(即空),結果返回沒有問題,只是我的下拉列表是空白的,從而阻止用戶從列表中選擇另一個項目。請重新填寫篩選器操作下拉列表或者是否有更簡單的方法來執行此操作?
以下是我的代碼的快照:
我的視圖模型
public class MyViewModel {
[DisplayName("Store")]
public IEnumerable<Store> StoreList { get; set; }
public string SelectedStore { get; set; }
}
我的視圖(Index.cshtml)
@using (Html.BeginForm()) {
<h2>Search</h2>
@Html.LabelFor(m => m.StoreList)
@Html.DropDownListFor(m => m.SelectedStore, new SelectList(Model.StoreList, "StoreCode", "StoreCode"), "Select Store")
<input type="submit" value="Filter" />
}
我的控制器:
public class MyController : Controller
{
public ActionResult Index() {
MyViewModel vm = new MyViewModel();
var storelist = new List<Store>();
storelist.Add(new Store { StoreCode = "XX" });
storelist.Add(new Store { StoreCode = "YY" });
storelist.Add(new Store { StoreCode = "ZZ" });
vm.StoreList = storelist;
return View(vm);
}
[HttpPost]
public ActionResult Index(MyViewModel model, string SelectedStore, FormCollection collection) {
if (ModelState.IsValid) {
/* this works, model state is valid */
/* BUT, the contents of model.StoreList is null */
}
return View(model);
}
}
感謝確認這對我來說和示例代碼 – tsiorn 2011-01-20 15:43:44