ModelState.IsValid是做什么的? [英] What does ModelState.IsValid do?

查看:1181
本文介绍了ModelState.IsValid是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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?

这是我的示例:

[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指示是否可以将请求中的传入值正确绑定到模型,以及在模型绑定期间是否违反了任何明确指定的验证规则过程.

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.

在您的示例中,要绑定的模型是类类型Encaissement.验证规则是在模型上通过使用在IValidatableObjectValidate()方法中-或仅在action方法的代码中添加的属性,逻辑和错误而指定的规则.

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.

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

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.

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

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

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

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.

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

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.

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

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

这篇关于ModelState.IsValid是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆