c# - ModelState.IsValid 是做什么的?

标签 c# asp.net-mvc modelstate

当我执行创建方法时,我将我的对象绑定(bind)到参数中,然后我检查 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 指示是否可以将来自请求的传入值正确绑定(bind)到模型,以及在模型绑定(bind)过程中是否违反了任何明确指定的验证规则。

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

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

这是一个验证属性和 IValidatableObject 可能如何在您的模型类上实现的示例:

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 属性。如果你这样做,它就不会被绑定(bind),错误也会被添加到你的 ModelState 中。

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

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

关于c# - ModelState.IsValid 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36893804/

相关文章:

asp.net - 使用 asp.net 4.5 OAuth 用 clientid 和 secret 注册谷歌

javascript - 您可以使用 asp.net mvc Json() 将 C# 字典转换为 Javascript 关联数组吗

asp.net-mvc-4 - ASP.NET MVC FluentValidation 与 ViewModel 和业务逻辑验证

asp.net-mvc - 部分 View 和 ModelState.AddModelError

entity-framework - ASP.NET MVC 4 ModelState 在传递 key 时无效

c# - Winform Datagridview cellclick 错误 - 索引超出范围

c# - 同一项目中的自定义控件和应用程序

c# - XmlSerializer - 具有不同属性的相同元素

c# - 使用 Javascript 将日期设置为 raddatepicker

asp.net-mvc - 如果我的应用程序使用 Azure "Easy Auth",如何向 Microsoft Graph 进行身份验证