How to customize Html.ValidationMessageFor in ASP MVC

后端 未结 7 860
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:14

    You can implement your own ValidationMessageFor helper to emit your desired output or use some javascript to add/modify the rendered HTML code but the custom ValidationMessageFor implementation is the cleaner approach IMHO.

    To implement your own ValidationMessageFor helper take a look at the ValidationExtensions.ValidationMessageFor and ValidationMessageHelper methods in the ASP.NET MVC source code.

    Implementation Hints

    Since GetFormContextForClientValidation is internal you have to work around that implementation by duplicating the internal functionality in your code:

    FormContext formContext = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
    

    Some other methods are private in ValidationExtensions like GetUserErrorMessageOrDefault you would need to duplicate that code too. What you can do to avoid duplicating code is to let ValidationExtentensions.ValidationMessageFor render the validation message string that is wrapped in a span and afterwards change the rendered string according to your requirements. Keep in mind that "null" is returned in case no error was found and that you'll need the data- HTML attributes in case you have unobtrusive JavaScript enabled.

    You can download the ASP.NET MVC 3 source code from here

    0 讨论(0)
提交回复
热议问题