標籤:狀態 efault ima 使用者 mvc 校正 empty ret reflect
*、這裡只做後台資料驗證,利用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 = "提交" />}
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