MVC中的MODEL验证
2011-03-29 19:08 撞破南墙 阅读(869) 评论(0) 编辑 收藏 举报
S1:添加部分类。和验证
using System.ComponentModel.DataAnnotations;
namespace STOA.RichModel {
[MetadataType(typeof(RoleValidation))]
public partial class Role {
}
public class RoleValidation {
[Editable(false)]
[Display(Name = "编号")]
public string RoleID { get; set; }
[Required]
[LengAttribute(MinLength = 5, MaxLength = 10, ErrorMessage = "长度不符合要求")]
[Display(Name = "姓名")]
public string Name { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "注释")]
public string Description { get; set; }
// [Required]
[Display(Name = "状态")]
public string State { get; set; }
}
//自定义的
public class LengAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute {
public override bool IsValid(object value) {
if (value == null || value.ToString().Length < MinLength || value.ToString().Length > MaxLength) {
return false;
}
return true;
}
public int MinLength { get; set; }
public int MaxLength { get; set; }
}
}
S2:调用验证 在 edit页面
[HttpPost]
[ValidateFilterAttribute(Description = "提交编辑")]
public ActionResult Edit(int id, STOA.RichModel.Role role) {
try {
if (!ModelState.IsValid) {
return View();
}
// TODO: Add update logic here
STOA.RichModel.STOADBContainer s = new RichModel.STOADBContainer();
var rolefromdb = s.Role.Where(_ => _.RoleID == role.RoleID).FirstOrDefault();
TryUpdateModel(rolefromdb);
s.SaveChanges();
return RedirectToAction("list");
} catch {
return View();
}
}
public ActionResult Edit(int id, STOA.RichModel.Role role) {
try {
if (!ModelState.IsValid) {
return View();
}
// TODO: Add update logic here
STOA.RichModel.STOADBContainer s = new RichModel.STOADBContainer();
var rolefromdb = s.Role.Where(_ => _.RoleID == role.RoleID).FirstOrDefault();
TryUpdateModel(rolefromdb);
s.SaveChanges();
return RedirectToAction("list");
} catch {
return View();
}
}
S3:显示在页面
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<STOA.RichModel.Role>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Edit</title>
</head>
<body>
<%: Html.ValidationSummary(true) %>
作者:撞破南墙
出处:http://www.cnblogs.com/facingwaller/
关于作者:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。