我有一個表格,其中有幾個輸入使用Html.TextBoxFor
,每個輸入都有一個ValidationMessageFor
,它從ViewModel
屬性獲取錯誤消息。在這個例子中,我們會假裝這裏只有一個輸入:MVC4表格輸入驗證 - 自定義錯誤範圍
@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跨度類別?
<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因爲我最初打算在創建解決方案。
控制器
ModelState.AddModelError("Code", "Invalid Code");
VIEW
@Html.CustomValidationMessage("Code")
延長
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);
}
}
你看到[這](http://stackoverflow.com/questions/5410665/custom-validationformessage-helper-removing -CSS元件/ 5412346#5412346)? – 2013-02-27 12:34:18