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.
[Required(ErrorMessage = "Please enter name")] public string Name { get; set; }
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.
if(!ModelState.IsValid) { var error = new ErrorModel(); error.Message = "Please correct the following errors"; foreach (var key in ModelState.Keys) foreach (var e in ModelState[key].Errors) error.ValidationMessages.Add(e.ErrorMessage); ViewBag.Error = error; }
For our extension method, we use an ErrorModel
. The model captures all the error messages. We store the object in the ViewBag
.
public class ErrorModel { public string Message { get; set; } public List<string> ValidationMessages { get; set; } // optional public ErrorModel() { ValidationMessages = new List<string>(); } }
Extension method
Our extension method is Error
. And it is invoked as follows.
<div class="error"> @Html.Error((ErrorModel)ViewBag.Error) </div>
In the above code, Html is an object of HtmlHelper
class. The Error method is an extension method.
public static class HtmlExtension { public static IHtmlString Error(this HtmlHelper helper, ErrorModel errorModel) { string html = string.Empty; if (errorModel != null) { html = errorModel.Message; if (errorModel.ValidationMessages.Count > 0) { html += "<ul>"; foreach (var validationMessage in errorModel.ValidationMessages) html += "<li>" + validationMessage + "</li>"; html += "</ul>"; } } return new HtmlString(html); } }
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.