Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c# - What does ModelState.IsValid do?

When I do a create method i bind my object in the parameter and then I check if ModelState is valid so I add to the database:

But when I need to change something before I add to the database (before I change it the ModelState couldn't be valid so I have to do it) why the model state still non valid.

What does this function check exactly?

This is my example:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EncaissementID,libelle,DateEncaissement,Montant,ProjetID,Description")] Encaissement encaissement) {
  encaissement.Montant = Convert.ToDecimal(encaissement.Montant);
  ViewBag.montant = encaissement.Montant;
  if (ModelState.IsValid) {
    db.Encaissements.Add(encaissement);
    db.SaveChanges();
    return RedirectToAction("Index", "Encaissement");
  };
  ViewBag.ProjetID = new SelectList(db.Projets, "ProjetId", "nomP");
  return View(encaissement);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. Validation rules are those specified on the model by the use of attributes, logic and errors added within the IValidatableObject's Validate() method - or simply within the code of the action method.

The IsValid property will be true if the values were able to bind correctly to the model AND no validation rules were broken in the process.

Here's an example of how a validation attribute and IValidatableObject might be implemented on your model class:

public class Encaissement : IValidatableObject
{
    // A required attribute, validates that this value was submitted    
    [Required(ErrorMessage = "The Encaissment ID must be submitted")]
    public int EncaissementID { get; set; }

    public DateTime? DateEncaissement { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        // Validate the DateEncaissment
        if (!this.DateEncaissement.HasValue)
        {
            results.Add(new ValidationResult("The DateEncaissement must be set", new string[] { "DateEncaissement" });
        }

       return results;
    }
}

Here's an example of how the same validation rule may be applied within the action method of your example:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EncaissementID,libelle,DateEncaissement,Montant,ProjetID,Description")] Encaissement encaissement) {

  // Perform validation
  if (!encaissement.DateEncaissement.HasValue)
  {
      this.ModelState.AddModelError("DateEncaissement", "The DateEncaissement must be set");
  }

  encaissement.Montant = Convert.ToDecimal(encaissement.Montant);

  ViewBag.montant = encaissement.Montant;

  if (ModelState.IsValid) {

    db.Encaissements.Add(encaissement);
    db.SaveChanges();
    return RedirectToAction("Index", "Encaissement");

  };

  ViewBag.ProjetID = new SelectList(db.Projets, "ProjetId", "nomP");

  return View(encaissement);
}

It's worth bearing in mind that the value types of the properties of your model will also be validated. For example, you can't assign a string value to an int property. If you do, it won't be bound and the error will be added to your ModelState too.

In your example, the EncaissementID value could not have a value of "Hello" posted to it, this would cause a model validation error to be added and IsValid will be false.

It is for any of the above reasons (and possibly more) that the IsValid bool value of the model state will be false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...