Model 验证

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;
            }
        }
    }


}

  

@{
    
}
@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>

  

posted @ 2022-01-25 08:11  zq爱生活爱代码  阅读(40)  评论(0编辑  收藏  举报