2

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

回答

3

是的,你必須重新填充是任何模型(包括ViewData的)傳遞給視圖。請記住,這是一個無狀態系統,您的控制器會在每次調用時重新實例化,並從頭開始有效地開始。

我就這樣做:

public class MyController : Controller 
{ 
    private List<Store> GetStoreList() 
    { 
      List<Store> StoreList = new List<Store>(); 
      // ... Do work to populate store list 
      return StoreList; 
    } 

    public ActionResult Index() { 

     MyViewModel vm = new MyViewModel(); 
     vm.StoreList = GetStoreList(); 
     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 */ 
     } 
     model.StoreList = GetStoreList(); 
     return View(model); 
    } 
} 
+0

感謝確認這對我來說和示例代碼 – tsiorn 2011-01-20 15:43:44

0

簡短的回答是肯定的,則需要重新在篩選器操作的下拉列表。 ASP.NET MVC不是WebForms - 沒有ViewState來保存列表的內容。

0

重新填寫下拉爲MVC沒有視圖狀態

[HttpPost] 公衆的ActionResult指數(MyViewModel型號,串SelectedStore,收集的FormCollection){

 if (ModelState.IsValid) { 
     /* this works, model state is valid */ 

     /* BUT, the contents of model.StoreList is null */ 
    } 
    model.StoreList = GetStoreList(); 
    return View(model); 
}