MVC错误&#34;属于&#39; System.Int32&#39;但必须是类型&#39; IEnumerable <selectlistitem>&#39;。 &#34; </selectlistitem>

时间:2014-04-25 12:21:27

标签: c# asp.net-mvc asp.net-mvc-4 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" })
        <div class="col-md-10">
            @Html.DropDownList("Names", String.Empty)
            @Html.ValidationMessageFor(model => model.Names)
        </div>
    </div>

现在点击“创建”按钮时出现错误

  

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

我收到此错误是因为ID是int,如果是,那我该怎么转换呢?

3 个答案:

答案 0 :(得分:1)

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

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

并在您的视图中,它是我们的viewmodel

的强类型
@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>

}

现在,当您的表单发布时,您将在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);
}

答案 1 :(得分:0)

在您的视图中使用此功能:

@Html.DropDownListFor(x => x.ID, ViewBag.Names, new Dictionary<string, object>{{"class", "control-label col-md-2"}})

这应该有效。

答案 2 :(得分:0)

在create:

的后期操作中再次填充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"}})