我有以下视图模型:
public class ViewModel
{
public Address Address {get;set;}
[DisplayName("State")]
public IEnumerable<SelectListItem> StateSelect { get; set; }
public string StateID { get; set; }
public ViewModel()
{
}
public ViewModel(Stuff s, IDataContext dc)
{
StateSelect = dc.States.ToList().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
Address = s.Address;
}
在我的编辑视图中:
<div class="display-field">
@Html.DropDownListFor(model => model.Address.StateID, Model.StateSelect,)
@Html.ValidationMessageFor(model => model.StateSelect)
</div>
我的控制器:
public ActionResult Edit(int id)
{
var stuff = context.Stuff.Find(id);
if (stuff== null)
{
throw new Exception("Stuff not found.");
}
return View(new ViewModel(stuff, context));
}
[HttpPost]
public ActionResult Edit(ViewModel model)
{
try
{
if (ModelState.IsValid)
{
//deeper logic, adds to ModelState.AddModelError
if(stillNotValid)
return View(model)
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
现在,在我Edit
看来,下拉列表已正确填充。但是,当我Edit
在控制器中发布到时,我的模型总是有一个空 StateSelect。
如何确保将 StateSelect 推送到我Edit
的帖子,以便在出现验证错误时可以重新填充下拉列表?