標籤:使用 strong os 問題 io cti
模型驗證通常在submit後調用Action之前進行驗證,eg:
public class ZhengXing
{
[Key]
public int ZhengXingId { get; set; } //使用Key關鍵字要引用System.ComponentModel.DataAnnotations
[DisplayName("標題")]
[Required(ErrorMessage = "請輸入標題")]
[MaxLength(60, ErrorMessage = "標題長度不能大於60個字元.")]
public string Title { get; set; }
[DisplayName("內容")]
[Required(ErrorMessage = "請輸入內容")]
[MaxLength(8000, ErrorMessage = "內容長度不能大於8000個字元.")]
public string Content { get; set; }
[DisplayName("作者")]
[Required(ErrorMessage = "作者不可為空")]
public string Author { get; set; }
[DisplayName("建立時間")]
public DateTime CreateDate { get; set; }
[DisplayName("閱讀次數")]
public int ClickCount { get; set; }
}
}
public ActionResult Create([Bind(Exclude="ZhengXingId")]ZhengXing zhengxing)
{
zhengxing.Author = Session["UserName"].ToString();
zhengxing.CreateDate = DateTime.Now;
if (ModelState.IsValid)
{
db.ZhengXings.Add(zhengxing);
db.SaveChanges();
return RedirectToAction("ManageIndex");
}
else
return View(zhengxing);
}
ZhengXing模型裡面有Title,Content,Author,CreateDate,ClickCount這幾個欄位,但是在create頁面僅僅給title和content賦值,並沒有給Author和CreateDate賦值,而是在後台賦值,但是每次ModelState.IsValid都為false,最後終於發現問題了,只要將模型裡的[Required(ErrorMessage = "作者不可為空")]注釋掉就行。
最終總結:ModelState.IsValid的驗證是在Submit後Action調用前進行模型驗證。