它看起来像一个合法的错误,这是我在搜索中找到的最佳解决方法:
http://forums.asp.net/t/1649193.aspx
简而言之。您将问题的根源包装DropDownListFor
在自定义 Html 扩展中,然后手动检索不显眼的客户端验证规则,如下所示:
IDictionary<string, object> validationAttributes = htmlHelper.
GetUnobtrusiveValidationAttributes(
ExpressionHelper.GetExpressionText(expression),
metadata
);
然后将您的validationAttributes
字典与传递给您的自定义帮助程序的任何其他 html 属性结合起来,然后将其传递给DropDownListFor
我正在使用的完整代码(我也有一个标签,你可以随意解耦):
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));
}