Mvc中的数据验证方法

Model代码:注意其中加了验证

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

namespace MvcValidateDemo.Models
{
    public class UserInfo
    {
        public int ID{ get;set; }
        [StringLength(5,ErrorMessage="长度必须小于5")]
        [Required(ErrorMessage="*姓名必填")]
        public string UserName{ get;set; }
        [Range(1,100,ErrorMessage="*年龄必须在1-100之间")]
        [Required(ErrorMessage = "*年龄必填")]
        public int Age { get; set; }

    }
}

view视图代码:

@model MvcValidateDemo.Models.UserInfo

@{
    Layout = null;
}
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Add</title>
</head>
<body>
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
    
        <fieldset>
            <legend>UserInfo</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.UserName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.UserName)
                @Html.ValidationMessageFor(model => model.UserName)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Age)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Age)
                @Html.ValidationMessageFor(model => model.Age)
            </div>
    
            <p>
                <input type="submit" value="注册" />
            </p>
        </fieldset>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

控制器代码:

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

namespace MvcValidateDemo.Controllers
{
    public class UserInfoController : Controller
    {
        

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(UserInfo uf)
        {
           if(ModelState.IsValid)
           {
               return RedirectToAction("index");
           }
           else
           {
               return View();
           }
           
        }
    }
}

在Medol中加入验证方法,在前端即可实现验证功能,提交到控制器的Add(UserInfo userInfo)方法时,在后台判断一下ModelState.IsValid即可,如果为true说明验证通过,返回index视图,如果为false则不通过!返回Add视图!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值