ASP.Net MVC 3 不显眼的客户端验证不适用于下拉列表 [英] ASP.Net MVC 3 unobtrusive client validation does not work with drop down lists
问题描述
我有一个简单的下拉列表,列表中的第一项有一个空值.如果我没有选择列表中的任何内容,客户端验证将忽略它.我使用注释属性在模型上根据需要设置了该字段.
I have a simple drop down list, the first item in the list has an empty value. If I do not select anything in the list the client validation ignores it. I have that field set up as required on the model using annotation attributes.
@Html.DropDownListFor(model => Model.CCPayment.State, UnitedStatesStates.StateSelectList)
[Required(ErrorMessage = "State is Required.")]
public string State
{
get
{
return _state;
}
set
{
_state = value;
}
}
有什么想法吗?我错过了什么吗?
any ideas? am I missing something?
推荐答案
它看起来像是一个合法的错误,这是我在搜索中找到的最佳解决方法:
It looks like a legitimate bug, here's the best workaround I've found in my search:
http://forums.asp.net/t/1649193.aspx
简而言之.您将问题的根源 DropDownListFor
包装在自定义 Html 扩展中,然后手动检索不显眼的客户端验证规则,如下所示:
In short. You wrap the source of the problem, DropDownListFor
, in a custom Html extension and you manually retrieve the unobtrusive clientside validation rules like this:
IDictionary<string, object> validationAttributes = htmlHelper.
GetUnobtrusiveValidationAttributes(
ExpressionHelper.GetExpressionText(expression),
metadata
);
然后,您将 validationAttributes
字典与传递给自定义助手的任何其他 html 属性结合起来,然后将其传递给 DropDownListFor
Then you combine your validationAttributes
dictionary with any other html attributes passed into your custom helper and you pass that along to DropDownListFor
我使用的完整代码(我也有一个标签,你可以随意解耦):
The complete code that I'm using (I have a label in there too, you can feel free to de-couple):
public static IHtmlString DropDownListWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string label, IEnumerable<SelectListItem> items, string blankOption, object htmlAttributes = null)
{
var l = new TagBuilder("label");
var br = new TagBuilder("br");
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var mergedAttributes = helper.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);
if (htmlAttributes != null)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(htmlAttributes))
{
object value = descriptor.GetValue(htmlAttributes);
mergedAttributes.Add(descriptor.Name, value);
}
}
l.InnerHtml = label + br.ToString(TagRenderMode.SelfClosing) + helper.DropDownListFor(expression, items, blankOption, mergedAttributes);
return MvcHtmlString.Create(l.ToString(TagRenderMode.Normal));
}
这篇关于ASP.Net MVC 3 不显眼的客户端验证不适用于下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!