Model 验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCDemo.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page." ; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page." ; return View(); } public ActionResult Method1() { Student stu = new Student() { name= "张三" , age=30 }; ViewData.Model = stu; return View(); } public ActionResult Method2() { Student stu = new Student() { name = "李四" , age = 30 }; ViewData.Model = stu; return View(); } public ActionResult Method3(FormCollection fc) { Student stu = new Student() { name = fc[ "name" ], age = Convert.ToInt32( fc[ "age" ]) }; ViewData.Model = stu; return View(); } [ModelFilter] public ActionResult Method4(Student s) { //Student stu = null; //if (ModelState.IsValid) //{ // stu = new Student() { name = s.name, age = s.age }; // ViewData.Model = stu; //} //stu = new Student() { name = "", age = 0,sex="" }; //ViewData.Model = stu; //ViewBag.ErrorMessage = ModelState.Values.Where(x => x.Errors.Count > 0).SelectMany(x => x.Errors).SelectMany(x => x.ErrorMessage).ToList(); ViewData.Model = s; return View( "Method1" ); } } public class Student { [Required(AllowEmptyStrings = false ,ErrorMessage = "Name属性不可为null" )] public string name { get ; set ; } [Range(20,30,ErrorMessage = "年龄必须在20-30中间" )] public int age { get ; set ; } [Domain( "M" , "F" , "m" , "f" ,ErrorMessage = "有效的{0}必须是{1}之一" )] public string sex { get ; set ; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )] public class DomainAttribute : ValidationAttribute { public IEnumerable< string > Values { get ; private set ; } public DomainAttribute( string value) { this .Values = new string [] { value }; } public DomainAttribute( params string [] values) { this .Values = values; } public override bool IsValid( object value) // 验证是否有效value是传递的值 { return this .Values.Any(item => value.ToString() == item); } public override string FormatErrorMessage( string name) // name 是栏位名称,验证失败走这一段 { string [] values = this .Values.Select(value => string .Format( "'{0}'" , value)).ToArray(); return string .Format( base .ErrorMessageString, name, string .Join( "," , values)); } } public class ModelFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.Controller.ViewData.ModelState.IsValid) { ///实体验证未通过 var ErrorMsg = string .Concat(context.Controller.ViewData.ModelState.Values.Where(x => x.Errors.Count > 0).SelectMany(x => x.Errors).SelectMany(x => x.ErrorMessage).ToList()); context.Result = new JsonResult() { Data= new {state=-1,errMessage= ErrorMsg } }; // 返回JSON string controller = context.RouteData.Values[ "controller" ].ToString(); string actionname=context.RouteData.Values[ "action" ].ToString(); //context.Result = new RedirectResult("~/Home/Method1"); // 返回重定向 return ; } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | @{ } @model MVCDemo.Controllers.Student <!DOCTYPE html> <html> <head> <meta name= "viewport" content= "width=device-width" /> <title></title> </head> <body> <script> $(function () { $( ".btn" ).click(function () { $.post( "Method4" , { name: $( "#name" ).val(), age: $( "#age" ).val(), sex: $( "#sex" ).val() }, function (result) { console.log(result); alert(result.errMessage); }) }); }); </script> <h1>Method1</h1> <div> @*@ foreach ( var item in @ViewBag.ErrorMessage) { @item }*@ </div> <div> @Model.name </div> <div> @Model.age </div> <div> @Model.sex </div> <div> @ using (Html.BeginForm( "Method4" , "Home" , FormMethod.Post)) { @Html.TextBox( "name" ) @Html.TextBox( "age" ) @Html.TextBox( "sex" ) <input type= "submit" value= "提交" /> <input type= "button" value= "ajax提交" class = "btn" /> } </div> </body> </html> |
分类:
ASP.NET MVC
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人