客户端验证已禁用:
public static IHtmlString ValidationLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText = null) {
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var name = ExpressionHelper.GetExpressionText(expression);
string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? name.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText)) {
return MvcHtmlString.Empty;
}
var tag = new TagBuilder("label");
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name)));
tag.GenerateId(name);
tag.SetInnerText(resolvedLabelText);
ModelState modelState;
string fullName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (html.ViewData.ModelState.TryGetValue(fullName, out modelState)) {
if (modelState.Errors.Count > 0) {
tag.Attributes.Add("style", "color:red");
}
}
return new MvcHtmlString(tag.ToString());
}
编辑
启用客户端验证
我真的不是 js 的王者,但这似乎有效(至少在一个简单的情况下)
$('form').submit(function () {
var form = $(this);
$('label').removeClass('field-validation-error');
if (!form.valid()) {
$('.input-validation-error')
.each(function () {
$("label[for='" + $(this).attr("id") + "']").addClass('field-validation-error');
});
}
});