ModelState.IsValid 是做什么的?

What does ModelState.IsValid do?

当我执行创建方法时,我将我的对象绑定到参数中,然后我检查 ModelState 是否有效,因此我添加到数据库中:

但是当我需要在添加到数据库之前更改某些内容时(在我更改它之前 ModelState 无效所以我必须这样做) 为什么模型状态仍然无效。

这个函数具体检查什么?

这是我的例子:

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

ModelState.IsValid 基本上会根据添加到模型属性的数据注释告诉您 post 发送到服务器的数据是否存在任何问题。

例如,如果您有一个 [Required(ErrorMessage = "Please fill")],并且当您 post 向服务器发送表单时 属性 为空,则 ModelState 将无效。

ModelBinder 还会为您检查一些基本内容。例如,如果您有一个 BirthDate 日期选择器,并且此选择器绑定到的 属性 不是可为空的 DateTime 类型,那么如果您将日期留空,您的 ModelState 也将无效。

Here, and here 是一些有用的 post 可供阅读。

ModelState.IsValid 表示是否可以将来自请求的传入值正确绑定到模型,以及在模型绑定过程中是否违反了任何明确指定的验证规则。

在您的示例中,绑定的模型是 class 类型 Encaissement。验证规则是通过使用在 IValidatableObjectValidate() 方法中添加的属性、逻辑和错误在模型上指定的规则 - 或者只是在操作方法的代码中。

如果值能够正确绑定到模型并且在此过程中没有违反验证规则,IsValid 属性 将为真。

这是一个验证属性和 IValidatableObject 可能如何在您的模型上实现的示例 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;
    }
}

下面是一个示例,说明如何在示例的操作方法中应用相同的验证规则:

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

请记住,模型属性的值类型也将得到验证。例如,您不能将字符串值分配给 int 属性。如果这样做,它不会被绑定,错误也会添加到您的 ModelState

在您的示例中,EncaissementID 值不能有值 "Hello" 发布到它,这将导致添加模型验证错误并且 IsValid 将为假.

由于上述任何原因(可能更多),模型状态的 IsValid 布尔值将是 false

您可以找到一篇关于 ModelState 及其用途的精彩文章 here

具体来说,IsValid 属性 是检查 ModelState.Errors 中是否存在任何字段验证错误的快速方法。如果您不确定是什么导致您的模型在 POST 到您的控制器方法时无效,您可以检查 ModelState["Property"].Errors 属性,它应该至少产生一个表单验证错误。

编辑:使用来自@ChrisPratt

的正确字典语法更新