MVC数据验证的使用

asp.net mvc会自动根据属性的类型进行基本的校验,比如如果属性是int类型的,那么在提交非整数类型的数据的时候就会报错。
注意ASP.net MVC并不是在请求验证失败的时候抛异常,而是把决定权交给程序员,程序员需要决定如何处理数据校验失败。在Action中根据ModelState.IsValid判断是否验证通过,如果没有通过下面的方法拿到报错信息:string errorMsg = WebMVCHelper.GetValidMsg(this.ModelState);
Models代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Layout.Models
{
    public class Tel
    {
        [Required(ErrorMessage = "必填")]
        [Display(Name = "手机号")]
        [RegularExpression(@"^1[34589][0-9]{9}$", ErrorMessage = "手机号码格式不正确!")]
        public string PhoneNumber { get; set; }
    }
}

视图层代码:

@model Layout.Models.Tel
@{
    Layout = null;
}





    
    Index


    

控制器代码:

using Layout.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Layout.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Tel tel)
        {
            if (ModelState.IsValid)
            {
                var script = String.Format("", Url.Action("Index"));
                return Content(script, "text/html");
            }
            else
            {
                string msg = Vaildate.GetError(ModelState);
                return Content(msg);
                //var script = String.Format("", Url.Action("Index"));
                //return Content(script, "text/html");
            }
        }
    }
}

新建一个类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Layout
{
    public static class Vaildate
    {
        public static string GetError(ModelStateDictionary modelState)
        {
            StringBuilder builder = new StringBuilder();
            foreach (var item in modelState.Keys)
            {
                if (modelState[item].Errors.Count <= 0)
                {
                    continue;
                }
                builder.Append("属性【").Append(item).Append("】错误
"); foreach (var error in modelState[item].Errors) { builder.AppendLine(error.ErrorMessage+"
"); } } return builder.ToString(); } } }

你可能感兴趣的:(MVC数据验证的使用)