基础拾遗-----数据注解与验证

前言

其实对于这块知识点,一直觉得没有必要进行总结,只是新到的公司当时用到了 kendo for asp.net mvc ,里面有用到,自动初始化页面,而依据基于对象属性的注解与验证,故此抽时间总计了一下吧。借鉴与《asp.net mvc 5高级编程》

验证注解的使用

数据注解定义在一般在命名空间”System.ComponentModel.DataAnnotations”提供了服务器端验证的功能,当在模型的属性上使用时,框架也支持客户端验证。在命名空间DataAnnotations总工有4个特性可以用于一般的验证场合。

1.Required 强调不能为空

[Required(ErrorMessage = "{0}不能为空")]
public Guid BID { get; set; }

2.StringLength控制字段长度

 [StringLength(4000, MinimumLength = 1, ErrorMessage = "{0}长度在{2}-{1}之间")] 
 public String Enclosure { get; set; }

3.RegularExpression正则表达式

[RegularExpression(@"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",ErrorMessage = "邮箱输入有误,重新输入。")]        
public string Email { get; set; }

4.Range指定值类型的范围

[Range(35,44,ErrorMessage = "年龄不符合要求")]
 public int Age { get; set; }

5.Compare两次输入必须一致

[RegularExpression(@"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",ErrorMessage = "邮箱输入有误,重新输入。")]        
public string Email { get; set; }
[Compare("Email ")]
public string Email2 { get; set; }

6.Remote 是mvc框架为应用程序在命名空间system.web.mvc额外添加的可以利用服务器端的回到函数执行客户端的验证逻辑

[Remote("CheckUserName", "Admin")]
public string UserName { get; set; }
public JsonResult CheckUserName(string username)
{
 return Json(DateTime.Now.ToString(),JsonRequestBehavior.AllowGet);
}

显示和编辑注解

1.DisplayName显示名称

  [DisplayName("金额(元)")]
  public Decimal Money { get; set; }

2.ScaffoldColumn可以隐藏HTML的辅助方法

[ScaffoldColumn(false)]
public string UserName { get; set; }

注:虽然ScaffoldColumn可以做到不显示一些属性在页面上被编辑,但是如果提交的Form有这个属性值,模型绑定机制依然会绑定此属性值。

3.DisplayFormat处理属性的各种格式。比如日期,浮点数等

[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:c}")]
public decimal Total { get; set; }

4.ReadOnly只读

        [DisplayName("计取时间")]
        [ReadOnly(true)]
        public string RememberTime { get; set; }

5.运行时提供关于属性的特定用途信息。

[Required(ErrorMessage = "密码不能为空")]
[DataType(DataType.Password)]
public string Password { get; set; }

自定义验证属性

其实这个方法就是定一个特性,进行验证。至于特性前面的文章有涉及。

下面对此的应用如下:

 [SelectList("/Inspect/GetSite?all=0",
             HttpVerbs.Post,
             CascadeFrom = "SegmentID",
             DataValueField = "SiteID",
             DataTextField = "Name",
             Data = @"function(){
                        return { segmentId: $(""#SegmentID"").val() };
                    }",
             DataType = "DropDownList")]
        [Required(ErrorMessage = "{0}不能为空")]
        public Guid SiteID { get; set; }

具体实现如下

 

[AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
    public class SelectListAttribute : Attribute, IMetadataAware
    {
        public SelectListAttribute(string remoteUrl, System.Web.Mvc.HttpVerbs httpVerbs = 1)
        {
            if (remoteUrl == null)
            {
                throw new ArgumentNullException("remoteUrl");
            }
            this.RemoteUrl = remoteUrl;
            this.HttpVerbs = httpVerbs;
            this.ServerFiltering = true;
        }
        
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }
            IDictionary<string, string> dictionary = null;
            if (!string.IsNullOrEmpty(this.AdditionalValues))
            {
                try
                {
                    dictionary = this.AdditionalValues.FromJson<IDictionary<string, string>>();
                }
                catch
                {
                    dictionary = new Dictionary<string, string>();
                }
                if ((dictionary != null) && (dictionary.Count > 0))
                {
                    foreach (KeyValuePair<string, string> pair in dictionary)
                    {
                        metadata.AdditionalValues[pair.Key] = pair.Value;
                    }
                }
            }
            metadata.AdditionalValues["RemoteUrl"] = this.RemoteUrl;
            metadata.AdditionalValues["Type"] = this.HttpVerbs;
            metadata.AdditionalValues["Data"] = this.Data;
            metadata.AdditionalValues["ServerFiltering"] = this.ServerFiltering;
            metadata.AdditionalValues["Events"] = this.ParseEvents(this.Events);
            metadata.AdditionalValues["CascadeFrom"] = this.CascadeFrom;
            metadata.AdditionalValues["Recursion"] = this.Recursion;
            metadata.AdditionalValues["Multiple"] = this.Multiple;
            metadata.AdditionalValues["DataTextField"] = this.DataTextField;
            metadata.AdditionalValues["DataValueField"] = this.DataValueField;
            metadata.DataTypeName = this.DataType;
        }
        
        private IDictionary<string, string> ParseEvents(string value)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    value = "{}";
                }
                return new Dictionary<string, string>(value.FromJson<IDictionary<string, string>>(), StringComparer.OrdinalIgnoreCase);
            }
            catch
            {
                return new Dictionary<string, string>();
            }
        }
        
        public string AdditionalValues { get; set; }
        
        public string CascadeFrom { get; set; }
        
        public string Data { get; set; }
        
        public string DataTextField { get; set; }
        
        public string DataType { get; set; }
        
        public string DataValueField { get; set; }
        
        public string Events { get; set; }
        
        public System.Web.Mvc.HttpVerbs HttpVerbs { get; private set; }
        
        public bool Multiple { get; set; }
        
        public bool Recursion { get; set; }
        
        public string RemoteUrl { get; private set; }
        
        public bool ServerFiltering { get; set; }
    }

至于特性请参考以前的文章:基础拾遗------特性详解

posted @ 2017-11-08 08:55  王延领  阅读(449)  评论(0编辑  收藏  举报