zoukankan      html  css  js  c++  java
  • 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%>
  • 相关阅读:
    弹窗多内容,灵活布局计算方式总结
    暖场广告设计方案
    UIStackView上手教程
    多弹窗排序总结
    常用的code snipper
    iOS开发常用技能点(持续更新中。。。)
    32位和64位系统区别及int字节数
    liunx环境,摄像头无法识别,解决方案
    TCP/IP 笔记 7 Ping
    TCP/IP 笔记 6 netstat -s 命令查看每个协议统计数据
  • 原文地址:https://www.cnblogs.com/facingwaller/p/1999099.html
Copyright © 2011-2022 走看看