Extension method extends an existing class. In this post, we will add an extension method to HtmlHelper class. The method display error messages.

Validation

Data annotations validates user input. An example is shown below.

Controller has the ModelState object. ModelState object has the validation errors. For each user input (eg. Name), there is a key within ModelState. And error messages are stored as values for the key.

For our extension method, we use an ErrorModel. The model captures all the error messages. We store the object in the ViewBag.

Extension method

Our extension method is Error. And it is invoked as follows.

In the above code, Html is an object of HtmlHelper class. The Error method is an extension method.

Error method wraps the error messages within an unordered list tag. The return type is IHtmlString.  Using the interface allows HTML tags within the string.

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