首页 > 代码库 > ASP.NET MVC3 ModelState.IsValid为false的问题
ASP.NET MVC3 ModelState.IsValid为false的问题
模型验证通常在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调用前进行模型验证。