Reputation: 401
Take this bit of generated code for example:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Bill bill)
{
if (ModelState.IsValid)
{
db.Entry(bill).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bill);
}
There is a Model called "Bill", that has some [Required] attributes set for it.
My question is: how does the ModelState.IsValid know that it should be checking the Bill entity as opposed to another entity?
Upvotes: 0
Views: 52
Reputation: 1039298
There's a default model binder in ASP.NET MVC called DefaultModelBinder
. This class will automatically execute for each of the action parameters you defined. And when it attempts to instantiate and populate the corresponding model from the request key/value string pairs, it might encounter errors that this model binder simply adds to the ModelState
dictionary. The reason why it might encounter errors is because you might have decorated your model with validation attributes.
So once the code execution enters the controller action, the ModelState.IsValid
property will return false if there are errors added to it during model binding.
By the way your code is equivalent to the following (never to be used, just for illustration purposes):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit()
{
Bill bill = new Bill();
if (TryUpdateModel(bill))
{
db.Entry(bill).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bill);
}
Upvotes: 1