代码改变世界

MVC中的MODEL验证

2011-03-29 19:08  撞破南墙  阅读(868)  评论(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 { getset; }


        [Required]
        [LengAttribute(MinLength 
= 5, MaxLength = 10, ErrorMessage = "长度不符合要求")]
        [Display(Name 
= "姓名")]
        
public string Name { getset; }

        [Required]
        [StringLength(
100)]
        [Display(Name 
= "注释")]
        
public string Description { getset; }

        
//  [Required]

        [Display(Name 
= "状态")]
        
public string State { getset; }
    }

//自定义的
    
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 { getset; }
        
public int MaxLength { getset; }
    }

} 

 

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();
            }
        }

 

 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%>