首页 > 代码库 > Asp.Net Mvc后台数据验证自测小Demo

Asp.Net Mvc后台数据验证自测小Demo

*、这里只做后台数据验证,利用mvc数据验证标记验证数据,并获取错误信息提示后页面中。

1、实现效果如下:

技术分享技术分享

 

2、model类 People.cs 

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

namespace WebTest.Areas.Validation.Models
{
    public class People
    {
        public int ID { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "用户名不可为空")]
        [StringLength(5)]
        public string Name { get; set; }


        [Required(AllowEmptyStrings = false, ErrorMessage = "密码不可为空")]
        public string Password { get; set; }
    }
}

3、视图Views:  Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>校验</h2>

@using (Html.BeginForm("Get", "Default", FormMethod.Post, new { @class = "MyForm", @id = "123" }))
{
    <p> 用户 </p > 
    @Html.TextBox("Name")  
    @Html.ValidationMessage("Name")
    <p> 密码 </p > @Html.TextBox("Password")
    @Html.ValidationMessage("Password")
    <input type = "submit" value = http://www.mamicode.com/"提交" />
}

4、控制器Controller:DefaultController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using WebTest.Areas.Validation.Models;

namespace WebTest.Areas.Validation.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Validation/Default
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Get(People p)
        {
            //验证模型状态字典的此实例是否有效
            if (ModelState.IsValid)
            {
                //验证通过,跳转
                return Redirect("");
            }
            else
            {
                //验证不通过,返回当前页面
                return View("Index");
            }
        }
    }
}

 

Asp.Net Mvc后台数据验证自测小Demo