7

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

1 Answer 1

11

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"] %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.