Mr *_*r A 2 validation asp.net-mvc asp.net-mvc-3 asp.net-mvc-2
调节器
var productList = Enumerable.Range(1, 80).Select(
x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }
);
ViewData["products"] = new SelectList(productList.ToList(), "Value", "Text");
Run Code Online (Sandbox Code Playgroud)
视图
<%: Html.DropDownList("products", ViewData["products"] as SelectList, "--select--")%>
<%: Html.ValidationMessage("products", "Please Select the Product from the List")%>
//This doesnt works on (ModelState.IsValid) I know the dropdown list data is coming
//from the view data not model , thats why model doesnt validate the particular dropdown
//list while it validates other fields which are linked to model,
//Just want to know, how can i validate the above dropdownlist
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 11
您将ddl的名称和值绑定到products.那是错的.当然,这是您的代码最少的问题.更大更严重的问题是您使用ViewData而不是使用强类型视图和视图模型.
所以有两种可能性:
糟糕的一个:在您的视图模型上有一个属性,您将绑定您的下拉值.
[Required(ErrorMessage = "Please Select the Product from the List")]
public string SelectedProduct { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后使用此属性名称作为弱类型DropDownList帮助程序和ViewData第二个agrument的第一个参数:
<%= Html.DropDownList(
"SelectedProduct",
ViewData["products"] as SelectList,
"--select--"
) %>
<%= Html.ValidationMessage("SelectedProduct") %>
Run Code Online (Sandbox Code Playgroud)正确的方法:当然是使用真实视图模型(我厌倦了重复它,只是谷歌,你会得到像我一样的gazillions答案,只是在这个主题的网站上).它看起来像这样:
<%: Html.DropDownListFor(
x => x.SelectedProduct,
Model.Products,
"--select--"
) %>
<%= Html.ValidationMessageFor(x => x.SelectedProduct) %>
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
10465 次 |
| 最近记录: |