I am just getting started with ASP.Net MVC 3 and am confused on this point.
In some examples when an action in a controller is run that contains inputs then a check is made to ensure ModelState.IsValid is true. Some examples do not show this check being made. When should I make this check? Must it be used whenever an input is provided to the action method?
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .
Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.
Clear() is required to display back your model object. If you are getting your Model from a form and you want to manipulate the data that came from the client form and write it back to a view, you need to call ModelState. Clear() to clean the ModelState values.
AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .
Must it be used whenever an input is provided to the action method?
It is exactly when you are using a view model provided as action argument and this view model has some validation associated with it (for example data annotations). Here's the usual pattern:
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With