• 【转载】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

  • 相关阅读:
    资源限制
    垃圾收集器
    GC日志
    happens-before
    maven相互依赖导致无法编译成功
    LVM-逻辑卷常用命令和示意图
    取消RAID5
    扩展RAID5的容量
    模拟RAID5损坏
    创建RAID5
  • 原文地址:https://www.cnblogs.com/Karson001/p/4531920.html
Copyright © 2020-2023  润新知