如何验证所选项目而无需在EmployeeViewModel中复制CompanyId?
public class EmployeeViewModel
{
[Required]
public int? Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public CompanyViewModel Company { get; set; }
public IEnumerable<CompanyViewModel> Companies { get; set; }
}
public class CompanyViewModel
{
[Required]
public int? Id { get; set; }
[Required]
public string Name { get; set; }
}
@Html.DropDownListFor(c => c.Company, Model.Companies, "-- Choose One --")
@Html.ValidationMessageFor(c => c.Company)
我原本期待这样的事情。
我知道,如果我将公司改为CompanyId int,它会正常工作,但我必须自己去取公司。
public class EmployeeViewModel
{
...
[Required]
public int? CompanyId { get; set; }
}
@Html.DropDownListFor(c => c.CompanyId, Model.Companies, "-- Choose One --")
@Html.ValidationMessageFor(c => c.CompanyId)
我在第一种方法中遗漏了什么?