*, here only to do background data validation, using MVC data validation tag validation data, and get error message prompt after the page.
1, the implementation of the results are as follows:
2. Model Class People.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingsystem.web;namespacewebtest.areas.validation.models{ Public classpeople { Public intID {Get;Set; } [Required (Allowemptystrings=false, errormessage ="user name cannot be empty")] [Stringlength (5)] Public stringName {Get;Set; } [Required (Allowemptystrings=false, errormessage ="The password cannot be empty")] Public stringPassword {Get;Set; } }}
3. View Views:Index.cshtml
@{Viewbag.title="Index";}@using (Html.BeginForm ("Get","Default", FormMethod.Post,New{@class ="MyForm", @id ="123" })){ <p> users </p >@Html. TextBox ("Name") @Html. Validationmessage ("Name") <p> password </p > @Html. TextBox ("Password") @Html. Validationmessage ("Password") <input type ="Submit"Value ="Submit"/>}
4, Controller Controller:DefaultController.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingsystem.web;usingSYSTEM.WEB.MVC;usingWebTest.Areas.Validation.Models;namespacewebtest.areas.validation.controllers{ Public classDefaultcontroller:controller {//Get:validation/default PublicActionResult Index () {returnView (); } PublicActionResult Get (People p) {//verifies that this instance of the model-state dictionary is valid if(modelstate.isvalid) {//verify pass, Jump returnRedirect (""); } Else { //validation does not pass, returns the current page returnView ("Index"); } } }}
ASP. NET MVC background data validation self-Test mini Demo