我有以下地址 ViewModel:
public class AddressViewModel
{
[StringLength(20, MinimumLength = 2, ErrorMessage = "Country name is too short")]
public String Country { get; set; }
public String City { get; set; }
public String Street { get; set; }
public String Number { get; set; }
public String ApartmentBuilding { get; set; }
public String Sector { get; set; }
}
以及呈现它的视图:
<div class="control-group offset2 span6">
@Html.LabelFor(m => m.Country)
<div class="controls">
@{
var countryCtrlName = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("Country");
Html.RenderAction("List", "Country", new { ControlName = countryCtrlName });
}
@Html.ValidationMessageFor(m => m.Country)
</div>
</div>
Html.RenderAction("List") 调用一个控制器方法,该方法从数据库中获取所有国家,并使用下拉列表呈现和呈现部分,这是视图:
@model IEnumerable<SelectListItem>
@{var controlName = (string)ViewBag.ControlName;}
@Html.DropDownList(controlName, Model, new {@class = ViewBag.CssClass})
即使我的 DropdownList 控件使用正确的名称呈现并因此在 POST 时映射到正确的 ViewModel,输入控件也没有使用必要的 data-val 属性进行装饰以启用客户端验证(我相信这是因为模型部分是 IEnumerable 而不是包含国家名称的字符串属性。
地址视图模型通过我的应用程序用作许多视图的嵌套属性。关于如何使其验证的任何想法?
编辑:根据@Robert 的回答更新了 ViewModel:
public class AddressViewModel { [StringLength(20, MinimumLength = 2, ErrorMessage = "Country name is too short")] public String Country { get; 放; }
public String City { get; set; }
public String Street { get; set; }
public String Number { get; set; }
public String ApartmentBuilding { get; set; }
public String Sector { get; set; }
public IEnumerable<CountryViewModel> CountryList {get; set;}
//Constructor to pass the list of countries
public AddressViewModel(IEnumerable<CountryViewModel> countries)
{
this.CountryList = countries;
}
}