模型不会为MVC中的默认值下拉列表生成错误

时间:2013-10-25 09:43:28

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 model

  C# code 
 public class customer
   {
    [Required]
    [Display(Name = "Country")]
    public int CountryId { get; set; } 
   }

ViewBag.CountryId = new SelectList(Uow.Countries.GetAll(),“Id”,“Name”);

  modelbuilder 
       modelBuilder.Entity<Customer>().HasRequired(p => p.Country)
                                      .WithMany(p => p.Customers)
                                      .HasForeignKey(p => p.CountryId)
                                      .WillCascadeOnDelete(false);




      <div class="control-group">
        @Html.LabelFor(model => model.CountryId, "CountryId", new { @class = "control-    label" })
          <div class="controls">
         @Html.DropDownList("CountryId","select country"); 
         @Html.ValidationMessageFor(model => model.CountryId, null, new { @class =  "help-inline" })
        </div>
        </div>

点击默认值为“保存”按钮时,我没有收到模型错误    “选择国家”“ 相反,我收到错误“ 具有键'CountryId'的ViewData项的类型为'System.Int32',但必须是'IEnumerable'类型

1 个答案:

答案 0 :(得分:1)

您下拉列表中的

CountryIdModel.CountryId,而不是ViewBag.CountryId。试试这个:

@Html.DropDownListFor(model => model.CountryId, (SelectList)ViewBag.CountryId,"select country"); 

我还建议您为集合选择不同的名称,并为获取选定值的属性选择。