我不明白为什么ModelState对于以下代码的帖子无效以及如何处理它。
我最初的行动:
public ActionResult Create()
{
InstitutionManager im = new InstitutionManager();
im.AddressTypeList = new SelectList(db.AddressTypes.Where(a => a.Active).ToList(), "Id", "Name");
return View(im);
}
我的帖子:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(InstitutionManager im)
{
if (ModelState.IsValid)
{
Institution inst = new Institution();
//Bunch of code here to save changes
db.Institutions.Add(inst);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(im);
}
我的观点导致问题的部分:
@Html.LabelFor(m => m.AddressTypeList, "Address Type", new { @class = "control-label ddlLabel sr-only" })
@Html.DropDownListFor(model => model.AddressTypeId, Model.AddressTypeList, "--Address Type--", new { @class = "form-control floatLabel ", placeholder = "Address Type" })
我的视图模型:
public class InstitutionManager
{
[Display(Name = "Institution Name")]
[Required]
public string Name { get; set; }
[Display(Name = "Address 1")]
[Required]
public string Address1 { get; set; }
public SelectList AddressTypeList { get; set; }
public string AddressTypeId { get; set; }
public int? Id { get; set; }
//Other stuff removed to simplify
}
这样可以正常工作并相应地填充下拉列表。但是当我发布表单时,ModelState无效。我假设它是因为SelectList现在是空的,但处理选择列表的正确方法是什么?我可以使用Viewbag,但我真的想将所有内容保存在viewmodel中。