如何获得完整控制如何处理[Required(ErrorMessage = "Title is required")]
等数据注释?
目前,我的系统会忽略所需的注释,因此在编辑时会接受空值。
奇怪的是,在数据库中没有改变,数据/字段完好无损。所以我的猜测是LINQ在本地存储了一些烦人的东西......
您需要更多详情吗?它基本上只是MVC2中的简单GET / POST动作方法。
修改
该模型如下所示:
public class HomeContent {
[Required(ErrorMessage = "* Id is required")]
public int Id { get; set; }
[Required(ErrorMessage = "* Title is required")]
[StringLength(50, ErrorMessage = "* Title is too long")]
public string Title { get; set; }
[Required(ErrorMessage = "* Content is required")]
[StringLength(8000, ErrorMessage = "* Content is too long")]
//8000 = varchar(MAX)
public string Content { get; set; }
[Required(ErrorMessage = "* You need to specify a language")]
public int Language { get; set; }
}
控制器操作如下所示:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult HomeControl(HomeContent homeContent) {
if (!DatabaseService.Instance.ModifyHomeContent(homeContent)) {
ViewData["Error"] = "An error occured during saving data to the page.";
} else {
ViewData["Error"] = "Changes has been saved!";
}
return View();
}
我发现在服务类方法调用周围包装if(ModelState.IsValid) { ... }
,它将完全验证数据注释。