Fork me on GitHub

李可

导航

ASP.NET MVC4系列验证机制、伙伴类共享源数据信息(数据注解和验证)

一,mvc前后台验证

自定义属性标签MyRegularExpression

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcAjaxValidate.Models
{
    public class MyRegularExpression:RegularExpressionAttribute
    {
        //为了多次修改正则,我们直接写一个类,只改这个地方就好//勿忘global文件
        //DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRegularExpression), typeof(RegularExpressionAttributeAdapter));

        public MyRegularExpression() : base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$") { }
    }
}

要起作用,需要在global文件注册适配器

     DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRegularExpression), typeof(RegularExpressionAttributeAdapter));

 

自定义model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAjaxValidate.Models
{
    public class DemoEntity
    {
        [Required(ErrorMessage = "*必填")]
        public int id { get; set; }

        [StringLength(10, ErrorMessage = "*长度小于10")]
        //[RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "必须邮箱")]
        [MyRegularExpression(ErrorMessage = "必须邮箱")]
        public string name { get; set; }

       // [Range(5, 10,ErrorMessage="5-10")]//数值,而不是长度
        
        [StringLength(5,ErrorMessage="最大5个字符")]
        //[MinLength(2,ErrorMessage="最小2个字符")]//不起作用,改成正则形式
        [RegularExpression(@"^.{2,}", ErrorMessage = "最小2个字符")]
        [DataType(DataType.Password)]
        public string password { get; set; }

        [DataType(DataType.Password)]
        [Compare("password", ErrorMessage = "密码要一致")]
        public string passwordRe { get; set; }
    }
}

controller action

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAjaxValidate.Models;

namespace MvcAjaxValidate.Controllers
{
    public class DemoEntityController : Controller
    {
        //
        // GET: /DemoEntity/

        public ActionResult create(DemoEntity demo)
        {
            if (ModelState.IsValid)
            {
                
            }
            return View();
        }

    }
}

view(create强类型视图)

@model MvcAjaxValidate.Models.DemoEntity

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>create</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script>    
        function complete() {
            alert(1)
        }

    </script>
    @using (Ajax.BeginForm("create", new AjaxOptions() {HttpMethod="post", Confirm="ok?" , OnComplete="complete"}))
    {
        @Html.ValidationSummary(true)
    
        <fieldset>
            <legend>DemoEntity</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.name)
                @Html.ValidationMessageFor(model => model.name)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.password)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.password)
                @Html.ValidationMessageFor(model => model.password)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.passwordRe)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.passwordRe)
                @Html.ValidationMessageFor(model => model.passwordRe)
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

二,常为ef自动生成实体类采用伙伴类的技术验证

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;//...
using System.Linq;
using System.Web;

namespace MvcAjaxValidate.Models
{   //伙伴类的技术,共享源数据信息
    //防止ef实体修改后,标签出被冲掉,我们换一个地方写。ef变 标签写到外面了,就不会丢了
    //让实体类和目标类共享信息,在这个类的所有属性,目标类就会有
    //这个类和目标类属性名一样哦
    //实体类和目标类要在一个命名空间!!!!!!!!!!!!!!!!
    [MetadataType(typeof(MetaTypeShare))]
    public partial class UserInfor
    {

    }
    //目标类
    public class MetaTypeShare
    {
        public int ID { get; set; }
        [Required(ErrorMessage="必填")]
        public string UName { get; set; }
        public string UPassword { get; set; }
        public Nullable<System.DateTime> USubTime { get; set; }
        public Nullable<System.DateTime> ULastMoltifyTime { get; set; }
        public Nullable<System.DateTime> ULastLoginTime { get; set; }
        public string UEmail { get; set; }
        public string UAddress { get; set; }
        public string UPhone { get; set; }
        public string URemark { get; set; }
        public Nullable<short> Usex { get; set; }
        public Nullable<short> UDelFlag { get; set; }
        public Nullable<int> UErrorCount { get; set; }
    }
    
}

 

posted on 2015-09-16 15:35  李可在江湖  阅读(476)  评论(0编辑  收藏  举报