简体   繁体   中英

How does the ModelStateDictionary in ASP.NET know which model to validate?

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM