MVC错误”;属于';System.Int32';但必须是';IEnumerable<;选择列表项

本文关键字:lt IEnumerable 选择 列表 Int32 错误 属于 System MVC | 更新日期: 2023-09-27 18:00:20

我有一个这样的模型;

    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" })
        <div class="col-md-10">
            @Html.DropDownList("Names", String.Empty)
            @Html.ValidationMessageFor(model => model.Names)
        </div>
    </div>

现在,当点击创建按钮时,我得到一个错误,说

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

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

MVC错误”;属于';System.Int32';但必须是';IEnumerable<;选择列表项

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

public class CreateCustomerVM
{
   public string MidName{ get; set; }
   [Required]
   public string FirstName{ get; set; }
   public string Surname{ get; set; }
   public List<SelectListItem> MidNames { set;get;}
   public CreateCustomerVM()
   {
     MidNames=new List<SelectListItem>();
   }
}

和在你的Create行动方法

public ActionResult Create()
{
  var vm=new CreateCustomerVM();
  vm.MidNames=GetMidNames();
  return View(vm);
}
private List<SelectListItem> GetMidNames()
{
  return new List<SelectListItem> { 
    new SelectListItem { Value="Mr", Text="Mr"},
    new SelectListItem { Value="Ms", Text="Ms"},
  };
}

在您看来,这是我们的视图模型的强类型

@model CreateCustomerVM
@using(Html.Beginform())
{
 <div>
   Mid name : @Html.DropdownListFor(s=>s.MidName,Model.MidNames)
   FirstName : @Html.TextBoxFor(s=>s.FirstName)
   <input type="submit" />
 </div>
}

现在,当您的表单发布后,您将在视图模型的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<string, object>{{"class", "control-label col-md-2"}})

这应该行得通。

在创建后的操作中再次填充在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<string, object>{{"class", "control-label col-md-2"}})