views:

24

answers:

1

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

+2  A: 

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"] %>
ewwwyn