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'类型
答案 0 :(得分:1)
CountryId
为Model.CountryId
,而不是ViewBag.CountryId
。试试这个:
@Html.DropDownListFor(model => model.CountryId, (SelectList)ViewBag.CountryId,"select country");
我还建议您为集合选择不同的名称,并为获取选定值的属性选择。