我有一个简单的下拉列表,列表中的第一项有一个空值.如果我没有在列表中选择任何内容,则客户端验证会忽略它.我使用注释属性在模型上根据需要设置了该字段.
@Html.DropDownListFor(model => Model.CCPayment.State,UnitedStatesStates.StateSelectList) [required(ErrorMessage = "State is required.")] public string State { get { return _state; } set { _state = value; } }
有任何想法吗?我错过了什么吗?
解决方法
它看起来像一个合法的错误,这是我在搜索中找到的最佳解决方法:
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)); }