Data annotations is used to validate user input.

The Controller class contains the Model State. If the Model State is not valid, the error messages are contained as dictionary, with the key corresponding to the name of the user input field.

ErrorModel is used to capture the error messages. The ErrorModel object is stored in the ViewBag for the View to display the error messages.

An extension method for HtmlHelper class ensures that the error messages are decorated with the appropriate HTML tags.

Extension methods are useful to extend classes that you have not written. HtmlHelper class is a part of Microsoft ASP.NET MVC framework. In the above code, Html is an object of HtmlHelper class. The Error method is an extension method which extends the HtmlHelper class.

The extension method wraps the error messages with the HTML list tag. The return is an IHtmlString. IHtmlString interface ensures that the HTML tags are not encoded.

An extension method for HtmlHelper to display error messages
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *