码迷,mamicode.com
首页 > Windows程序 > 详细

【转载】C#后台声明式验证,远离if验证

时间:2015-05-26 23:27:06      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

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

【转载】C#后台声明式验证,远离if验证

标签:

原文地址:http://www.cnblogs.com/Karson001/p/4531920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!