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?
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.
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