【发布时间】:2013-02-21 20:28:30
【问题描述】:
我有以下地址 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:
公共类 AddressViewModel { [StringLength(20, MinimumLength = 2, ErrorMessage = "国家名称太短")] 公共字符串国家{得到;放; }
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;
}
}
【问题讨论】:
-
我不熟悉
KDropDownList。谷歌告诉我它是Keyoti.Search的一部分。对吗? -
KDropDownList 是我做的一个扩展,它用一些额外的类装饰下拉列表。和调用 Html.DropDownListFor 一样(为了可读性我还是更新了代码)
标签: c# asp.net asp.net-mvc