Html.ValidationMessage in MVC

When there is an error for a particular field in the ModelState dictionary, you can use the ValidationMessage helper to display that message. For example, in the following controller action, you purposely add an error to model state for the Title property:

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var album = storeDB.Albums.Find(id);
ModelState.AddModelError("Title", "What a terrible name!");
return View(album);
}

In the view, you can display the error message (if any) with the following code:

@Html.ValidationMessage("Title")

which results in:

<span class="field-validation-error" data-valmsg-for="Title" data-valmsg-replace="true">
What a terrible name!
</span>

This message appears only if there is an error in the model state for the key Title. You can also call an override that allows you to override the error message from within the view:

@Html.ValidationMessage("Title", "Something is wrong with your title")

which results in:

<span class="field-validation-error" data-valmsg-for="Title" data-valmsg-replace="false">Something is wrong with your title</span>

In addition to the common features described so far, such as HTML encoding and the ability to set HTML attributes, all the form input features share some common behavior when it comes to working with model values and model state.

Tagged . Bookmark the permalink.

Leave a Reply