我有一个使用Html.TextBoxFor
的多个输入的表单,每个输入都有ValidationMessageFor
,它从ViewModel
属性中获取错误消息。对于这个例子,我们假装只有一个输入:
@Html.TextBoxFor(x => x.Code)
@Html.ValidationMessageFor(x => x.Code)
当出现模型错误时,验证器会在几个跨度内显示它的错误消息,如下所示:
<input type="text" value="" name="Code" id="Code" data-val-required="Personalised code is required" data-val="true" class="input-validation-error">
<span data-valmsg-replace="true" data-valmsg-for="Code" class="field-validation-error">
<span for="Code" generated="true" class="">Personalised code is required</span>
</span>
如何自定义此错误消息?
例如,将外跨度更改为div并同时给出div和span clases?
<div class="myOuterSpan" data-valmsg-replace="true" data-valmsg-for="Code" class="field-validation-error">
<span class="myInnerSpan" for="Code" generated="true" class="">Personalised code is required</span>
</div>
或者只有一个跨度?
<span class="errorWrapper" for="Code" generated="true">Code is required</span>
或者将整个地块包裹在div中?
<div class="myOuterDiv">
<span data-valmsg-replace="true" data-valmsg-for="Code" class="field-validation-error">
<span for="Code" generated="true" class="">Personalised code is required</span>
</span>
</div>
你明白了......
解决方案
我的解决方案基于Darin的答案并创建了一个CustomValidationMessage,而不是我最初打算创建的customValidationMessageFOR。
CONTROLLER
ModelState.AddModelError("Code", "Invalid Code");
查看
@Html.CustomValidationMessage("Code")
EXTENSION
public static class Extensions
{
public static MvcHtmlString CustomValidationMessage(this HtmlHelper htmlHelper, string modelName)
{
var modelState = htmlHelper.ViewData.ModelState[modelName];
var modelErrors = modelState == null ? null : modelState.Errors;
var modelError = ((modelErrors == null) || (modelErrors.Count == 0))
? null
: modelErrors.FirstOrDefault(e => !string.IsNullOrEmpty(e.ErrorMessage)) ?? modelErrors[0];
if (modelError != null)
{
return MvcHtmlString.Create("<span class='validation_wrapper customValidation'><span>" + modelError.ErrorMessage +"</span></span>");
}
return new MvcHtmlString(string.Empty);
}
}
答案 0 :(得分:5)
无法修改ValidationMessageFor
帮助程序生成的标记。如果你想这样做,你将不得不写一个自定义助手。以下是此助手的签名可能如下所示:
public static MvcHtmlString CustomValidationMessageFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
...
}
您也可以结帐similar post
。
答案 1 :(得分:1)
实际上不需要自定义扩展程序。例如:
控制器:
ModelState.AddModelError("InvalidLogin", "Your credentials are invalid.")
查看:
@Html.ValidationMessageFor
(
model => model.InvalidLogin,
"",
htmlAttributes: new { @class = "text-error" },
tag: "div"
)