ASP.Net MVC 3 ModelState.IsValid

I am just getting started with ASP.Net MVC 3 and am confused about this issue.

In some examples, when an action is performed in the controller containing the inputs, a check is performed to ensure that ModelState.IsValid is true. Some examples do not show this check. When should I do this check? Should it be used whenever input is provided to an action method?

+4
source share
2 answers

Should it be used whenever an input is provided for an action method?

This is accurate when you use the presentation model presented as an action argument, and this presentation model has some validation associated with it (for example, data annotations). Here's a regular template:

public class MyViewModel { [Required] public string Name { get; set; } } 

and then:

 [HttpPost] public ActionResult Foo(MyViewModel model) { if (!ModelState.IsValid) { // the model is not valid => we redisplay the view and show the // corresponding error messages so that the user can fix them: return View(model); } // At this stage we know that the model passed validation // => we may process it and redirect // TODO: map the view model back to a domain model and pass this domain model // to the service layer for processing return RedirectToAction("Success"); } 
+7
source

Yes. It is mainly used for actions marked with the [HttpPost] attribute.

Imho view models should always be validated (and therefore always have some kind of validation, usually DataAnnotation attributes).

 public class MyViewModel { [Required] // <-- this attribute is used by ModelState.IsValid public string UserName{get;set;} } 

If you are interested in error handling in MVC, I wrote about this a couple of days ago.

+2
source

Source: https://habr.com/ru/post/1381191/


All Articles