Showing MVC ModelState errors in the view

I wanted to show the various ModelState errors encountered in an MVC controller and display them in the view. So in my controller, I have a bit of code that loops through the errors and builds them in a string, adding an HTML line break between each error:

string errors = String.Empty;

foreach (ModelState modelState in ViewData.ModelState.Values) {
     foreach (ModelError error in modelState.Errors) {
          errors += “<br />” + error.ErrorMessage;

ViewBag.Message = “The following errors have occurred: “ + errors;

In the view, I show my ViewBag variable. Notice that I use the Html.Raw method to display the HTML code properly in using Razor:



  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: