0
  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”类型"

4

1 回答 1

1

CountryId在你的下拉列表中是Model.CountryId,不是ViewBag.CountryId。尝试这个 :

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

我还建议您为您的收藏选择不同的名称以及获取选定值的属性。

于 2013-10-25T09:52:45.150 回答