MVC中的MODEL验证

 

 

 

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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值