How to customize Html.ValidationMessageFor in ASP MVC

后端 未结 7 870
Happy的楠姐
Happy的楠姐 2020-12-05 07:46

Is it possible to customize the Html.ValidationMessageFor method so that it produces different HTML?

I want to do something similar to:

7条回答
  •  日久生厌
    2020-12-05 08:09

    I am not sure if it's possible to use paragraph instead of default span, as it may make impossible for validation plugin to place error messages. But for div -s, thats easy - you could write custom html helper.

    Something along these lines (may need further testing/coding). You will need to include the namespace of this static extension method in your view, or put this into System.Web.Mvc.Html directly.

    public static class Validator
    {
        public static MvcHtmlString MyValidationMessageFor(this HtmlHelper helper, Expression> expression)
        {
            TagBuilder containerDivBuilder = new TagBuilder("div");
            containerDivBuilder.AddCssClass("field-error-box");
    
            TagBuilder topDivBuilder = new TagBuilder("div");
            topDivBuilder.AddCssClass("top");
    
            TagBuilder midDivBuilder = new TagBuilder("div");
            midDivBuilder.AddCssClass("mid");
            midDivBuilder.InnerHtml = helper.ValidationMessageFor(expression).ToString();
    
            containerDivBuilder.InnerHtml += topDivBuilder.ToString(TagRenderMode.Normal);
            containerDivBuilder.InnerHtml += midDivBuilder.ToString(TagRenderMode.Normal);
    
            return MvcHtmlString.Create(containerDivBuilder.ToString(TagRenderMode.Normal));
        }
    }
    

    As you see, this uses default ValidationMessageFor method, to not interfere with validation-plugin error message processing.

    And you use this simply, as default validation message helper

    @Html.MyValidationMessageFor(model => model.SomeRequiredField)
    

提交回复
热议问题