Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3 ModelState.IsValid

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?

like image 213
w.donahue Avatar asked Nov 14 '11 20:11

w.donahue


People also ask

What is ModelState IsValid in ASP NET MVC?

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 .

What is ModelState IsValid in asp net core?

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.

What is ModelState Clear () in MVC?

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.

How do I display ModelState errors?

AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .


1 Answers

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");
}
like image 159
Darin Dimitrov Avatar answered Sep 18 '22 22:09

Darin Dimitrov