ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Model 验证

2022-01-25 08:33:40  阅读:101  来源: 互联网

标签:string 验证 age stu Student Model public name


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>

  

标签:string,验证,age,stu,Student,Model,public,name
来源: https://www.cnblogs.com/JerryZhang320/p/15841618.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有