zoukankan      html  css  js  c++  java
  • 【转载】C#后台声明式验证,远离if验证

    ViewModel

     public class ViewModel
        {
    
            [Required(ErrorMessage="标题不能为空")]
            public string Title { get; set; }
    
    
    
            public string Name { get; set; }
    
    
    
        }
    

    后台验证代码

    public async Task<ActionResult> Save(ViewModel vm)
            {
                var validationContext = new ValidationContext(vm);
                var results = new List<ValidationResult>();
                var isValid = Validator.TryValidateObject(vm, validationContext, results, true); 
                if (!isValid)
                {
                    return Json(new { Result = false, Msg = results.Select(x => x.ErrorMessage).FirstOrDefault() });
                }
                return Json(new { Result = true, Msg = "成功!" });
            }
    

      

    前台调用:

    $.ajax({
                type: "post",
                url: "/home/save",
                data: "title=&name=11222332",
                dataType:"json", 
                success: function(data) {
                     alert(data.Msg);
                } 
            });
    

      

    原文地址:http://www.cnblogs.com/dudu/p/annotation-based-validation.html#3100481

  • 相关阅读:
    Go语言操作etcd
    grafana使用
    Java整理
    Go操作MySQL
    Go语言操作Redis
    es
    influxDB
    gopsutil
    Java基础之(三):IDEA的安装及破解 lyl
    ClojureScript 点访问格式
  • 原文地址:https://www.cnblogs.com/Karson001/p/4531920.html
Copyright © 2011-2022 走看看