gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:29:46 26 4
gpt4 key购买 nike

当我执行创建方法时,我将我的对象绑定(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com