public class CreateCustomerVM { public string MidName{ get; set; } [Required] public string FirstName{ get; set; } public string Surname{ get; set; } public List MidNames { set;get;} public CreateCustomerVM() { MidNames=new List(); } }
并在您的Create操作方法中
public ActionResult Create() { var vm=new CreateCustomerVM(); vm.MidNames=GetMidNames(); return View(vm); } private List GetMidNames() { return new List { new SelectListItem { Value="Mr", Text="Mr"}, new SelectListItem { Value="Ms", Text="Ms"}, }; }
Mid name : @Html.DropdownListFor(s=>s.MidName,Model.MidNames) FirstName : @Html.TextBoxFor(s=>s.FirstName)
}
现在,当您的表单发布时,您将在viewmodel的MidName属性中获取所选项目值。
[HttpPost] public ActionResult Create(CreateCustomerVM customer) { if(ModelState.IsValid) { //read customer.FirstName , customer.MidName // Map it to the properties of your DB entity object // and save it to DB } //Let's reload the MidNames collection again. customer.MidNames=GetMidNames(); return View(customer); }
在您的视图中使用此选项:
@Html.DropDownListFor(x => x.ID, ViewBag.Names, new Dictionary{{"class", "control-label col-md-2"}})
这应该工作。
在create的post动作中再次填充viewbag:
public ActionResult Create(){ ViewBag.Names= new SelectList(db.TbName, "ID", "MidName"); return View(); } [HttpPost] public ActionResult Create(){ ViewBag.Names= new SelectList(db.TbName, "ID", "MidName"); return View(); }
或尝试使用这样的帮助:
@Html.DropDownListFor(x => x.ID, (SelectList)ViewBag.Names, new Dictionary{{"class", "control-label col-md-2"}})