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

时间:2022-12-06 16:37:24

使用过MVC的同学一定不陌生MVC的模型绑定和模型校验,使用起来非常方便,定义好Entity之后,在需要进行校验的地方可以打上相应的Attribute,在Action开始时检查ModelState的IsValid属性,如果校验不通过直接返回View,前端可以解析并显示未通过校验的原因。

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

1、实现效果如下:

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

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()]
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 = "" }))
{
<p> 用户 </p >
@Html.TextBox("Name")
@Html.ValidationMessage("Name")
<p> 密码 </p > @Html.TextBox("Password")
@Html.ValidationMessage("Password")
<input type = "submit" value = "提交" />
}

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