MVC错误“属于’System.Int32’类型,但必须是’IEnumerable ‘类型。 “

我有这样的模特;

public int ID{ get; set; } public string MidName{ get; set; } public string FirstName{ get; set; } public string Surname{ get; set; } 

这是我的控制器:

  public ActionResult Create(){ ViewBag.Names= new SelectList(db.TbName, "ID", "MidName"); return Viwe(); } 

这是我的观点

  @Html.LabelFor(model => model.Names, new { @class = "control-label col-md-2" }) 
@Html.DropDownList("Names", String.Empty) @Html.ValidationMessageFor(model => model.Names)

现在,当单击“创建”按钮时,我收到错误消息

`具有键’Names’的ViewData项的类型为’System.Int32’,但必须是’IEnumerable’类型。

我得到这个错误是因为ID是int,如果是,那么我如何转换它?

我个人更喜欢尽可能避免像ViewBag / ViewData这样的动态内容在操作方法和视图之间传输数据。 让我们构建一个强类型的Viewmodel。

 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"}, }; } 

在您的视图中,这是我们的viewmodel强类型

 @model CreateCustomerVM @using(Html.Beginform()) { 
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"}})