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"] %>
Evan nagle
source share