【发布时间】:2011-06-12 11:12:43
【问题描述】:
我是 MVC2/3 的新手,所以请记住这一点。此外,也不能使用 Ajax 或 jQuery。
我有一个网页,用户必须从下拉列表中选择一个项目,然后点击“过滤器”按钮。 (单击此按钮将简单地触发我的控制器中的默认 POST 操作并返回过滤后的结果列表。
除了遇到一个问题外,我一切正常。当 Filter 操作完成并将控制权返回给我的视图时,下拉列表内容将丢失(即 null)。结果返回没有问题,只是我的下拉列表是空白的 - 从而阻止用户从列表中选择另一个项目。
我应该重新填写过滤操作的下拉列表还是有更简洁的方法来做到这一点?
这是我的代码快照:
我的视图模型
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);
}
}
【问题讨论】:
标签: asp.net-mvc-2 controller html.dropdownlistfor asp.net-mvc-3