How to check model validation errors in asp.net mvc?

How to check from inside the View, if there are any ModelState errors for a particular key (the key is the field key of the model)

+7
validation asp.net-mvc
source share
1 answer

If you haven’t already done so, check out this wiki on the MVC template .

Keep in mind that your view should be responsible for displaying data. So you should try to keep the amount of logic in your view to a minimum. If possible, handle ModelState errors (since 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 need to handle ModelState errors in your view, you can do it like this:

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

But keep in mind that you can do the same thing with your controller and thus remove unnecessary logic from your view. To do this, you can put the ModelState logic in the 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 opinion, you can refer to the TempData message, which removes the idea of ​​unnecessary logical creation:

  <%= TempData["ErrorMessage"] %> 
+11
source share

All Articles