Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.IsValid or Model.IsValid?

I'm writing a controller and unit tests for it, when I came across two ways (equally valid I think) to do something. All my models have an IsValid property, which I can check to ask the model if it's valid or not.

On postback to a controller action method, if the model is valid I want to save, otherwise I want to redisplay the form for the user to correct their errors.

My initial thought was to just verify that the model is being asked if it's valid, but I realized I could also check ModelState.IsValid.

Does anyone have any particular reason to look at one vs the other?

like image 741
Andy Avatar asked Feb 16 '11 00:02

Andy


1 Answers

I think having custom business validation built into your model is a fine approach. The way I would handle it would be to add any custom validation errors to the ModelState:

if (ModelState.IsValid)
{
    if (!model.IsValid)
    {
       ModelState.AddModelError("The model is not valid");
    }
    else
    {
        return RedirectToAction("Index");
    }
}

return View(model);

That way your view has access to the validation errors regardless of whether they are custom or built in.

like image 159
MrDustpan Avatar answered Oct 04 '22 17:10

MrDustpan