ASP.NET MVC 4 – Model + Validation ( Regular Expression ) 方法
Model |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Globalization; using System.Web.Security; namespace MvcApplication.Models { public class RegularPattern { public int id { get; set; } [Required] [RegularExpression("[A-Za-z0-9]", ErrorMessage = "Invalid Format")] public string regular_pattern { get; set; } } } |
Controller |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication.Controllers { public class HomeController : Controller { … … public ActionResult Form() { … … return View(); } [HttpPost] public ActionResult Form(MvcApplication.Models.RegularPattern model) { … … return View(model); } } } |
View |
@model MvcApplication.Models.RegularPattern @if(Model != null){ <span>Result</span> }else{ using(Html.BeginForm()){ @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div>@Html.TextBoxFor(x => x.regular_pattern)</div> <div>@Html.ValidationMessageFor(x => x.regular_pattern)</div> <br /> <input type="submit" value="Submit" /> } } @section Scripts { @Scripts.Render("~/bundles/jqueryval") } |