ModelState.IsValid指示是否可以將來自請求的傳入值正確綁定到模型,以及是否有任何明確指定的驗證規則在模型綁定過程中被破壞。
在你的例子中,被綁定的模型屬於類型Encaissement
。驗證規則是通過在IValidatableObject
的Validate()
方法中添加的屬性,邏輯和錯誤(或僅在操作方法的代碼內)在模型上指定的規則。
如果IsValid
屬性將爲true,如果值能夠正確綁定到模型並且沒有驗證規則在過程中被破壞。
這裏有一個如何驗證屬性和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
屬性。如果你這樣做,它不會被綁定,錯誤也會被添加到你的ModelState
。
在您的示例中,EncaissementID
值的發佈值不能爲"Hello"
,這會導致添加模型驗證錯誤,並且IsValid
將爲false。
由於上述任何一個原因(也可能更多),模型狀態的IsValid
布爾值將是false
。
您的模型有任何必需的屬性嗎?如果沒有輸入任何必填字段,模型狀態將無效。 –
輸入了所有必需的屬性,但我的模型狀態仍然無效! – kokomoi
看看我的答案,也許您的視圖綁定到不可爲空的int或datetime,並且這也會導致ModelState無效。 –