通常咱們作驗證都是前端驗證加後臺驗證,然而在MVC裏 咱們能夠在Model層就能夠前端
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace mytest2.Models { public class guests { [Key] [Required(ErrorMessage="請輸入名字")] public string name { get; set; } [Required(ErrorMessage = "請輸入電話號碼")] public string phone { get; set; } } }
[HttpPost] public ActionResult Guest(guests guests) { if(ModelState.IsValid) { return Content("success"); } else { if(string.IsNullOrEmpty(guests.name)) { ModelState.AddModelError("name","姓名不能爲空"); } } return View(); }
<form method="post"> <span>第一個 </span> @Html.ValidationSummary(true) <span></span><input id="name" name="name" /> <p>@Html.ValidationMessageFor(m => m.name)</p> <span></span><input id="phone" name="phone" /> <p>@Html.ValidationMessageFor(m => m.phone)</p> <button type="submit" >anniu</button> </form>