Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for Model validation errors in asp.net mvc?

How to check from inside the View if there are any ModelState errors for specific key (key is the field key of the Model)

like image 640
Inez Avatar asked Jun 14 '10 20:06

Inez


1 Answers

If you haven't yet, check out this wiki article on the MVC pattern.

Keep in mind that your view is only supposed to be in charge of displaying data. As such, you should try to keep the amount of logic in your view to a minimum. If possible, then, handle ModelState errors (as ModelState errors are the result of a failed model binding attempt) in your controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (!ModelState.IsValid)
        {
            return RedirectToAction("wherever");
        }

        return View();
    }
}

If you have to handle ModelState errors in your view, you can do so like this:

<% if (ViewData.ModelState.IsValidField("key")) { %>
    model state is valid
<% } %>

But keep in mind that you can accomplish the same thing with your controller and thus remove the unnecessary logic from your view. To do so, you could place the ModelState logic in your controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (!ModelState.IsValidField("key"))
        {
            TempData["ErrorMessage"] = "not valid";
        }
        else
        {
            TempData["ErrorMessage"] = "valid";
        }

        return View();
    }
}

And then, in your view, you can reference the TempData message, which relieves the view of any unnecessary logic-making:

    <%= TempData["ErrorMessage"] %>
like image 191
Evan Nagle Avatar answered Sep 19 '22 03:09

Evan Nagle