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