Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Server side Verification of ASP.NET MVC5

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of ASP.NET MVC5 server verification. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Data annotation API is used for server-side verification. When the ASP.NET MVC framework executes, it validates all the data passed to the controller. If the verification fails, it populates the error message into the ModelState object and passes the object to the controller. Then the method in the controller determines whether the verification fails or passes according to the state of the Modelstate.

Here, I will use two methods to verify the validity of the data, one is to manually add an error message to the ModelState object, and the other is to use the data annotation [Data Annotation] API to do so.

Let's take a look at the use of manual validation:

Let's create a new blank MVC project: add a Student entity:

Using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Server_Side_Validation_IN_MVC.Models {public class Student {public string Name {get; set;} public string Email {get; set;}

Then add a Student controller:

Using Server_Side_Validation_IN_MVC.Models;using System;using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;using System.Web;using System.Web.Mvc;namespace Server_Side_Validation_IN_MVC.Controllers {public class StudentController: Controller {/ / GET: Student public ActionResult Index () {return View () } [HttpPost] public ActionResult Index (Student model) {/ / server verification, method 1, manually add an error message to the ModelState object / / if the Name is empty if (string.IsNullOrEmpty (model.Name)) {ModelState.AddModelError ("Name", "Name is required") } / / if Email is empty if (string.IsNullOrEmpty (model.Email)) {ModelState.AddModelError ("Email", "Email is required") } else {string emailRegex = @ "^ ([a-zA-Z0-9 _\ -\.] +) @ (\ [[0-9] {1 a-zA-Z0 3}" + @ "\. [0-9] {1 a-zA-Z0 3}\. [0-9] {1 a-zA-Z0 3}\.) | ([a-zA-Z-9\ -] +\" + @ ".) ([a-zA-Z] {2pm 4} | [0-9] {1Magne3}) (\]?) $" Regex re = new Regex (emailRegex); / / when Email is not empty, but the format is invalid if (! re.IsMatch (model.Email)) {ModelState.AddModelError ("Email", "Email is not valid");}} / / entity verification passed if (ModelState.IsValid) {ViewBag.Name = model.Name; ViewBag.Email = model.Email;} return View (model);}

Create an Index view:

@ model Server_Side_Validation_IN_MVC.Models.Student@ {Layout = null } Index @ using (Html.BeginForm ()) {/ / use ViewData.ModelState.IsValid to determine the status of ModelState if (ViewData.ModelState.IsValid) {if (ViewBag.Name! = null) {Name:@ViewBag.Name Email:@ViewBag.Email}} Student @ * generate label tag * @ @ Html.LabelFor (model= > model.Name) @ * generate text box * @ @ Html.EditorFor (model= > model.Name) @ * illegal * / @ if (! ViewData.ModelState.IsValid) / / the correct way to write a problem is: @ if (! ViewData.ModelState.IsValid & & ViewData.ModelState ["Email"] .Errors.Count > 0) {/ / get the error message from the dictionary: @ ViewData.ModelState ["Name" "] .Errors [0] .ErrorMessage @ ViewData.ModelState [" Name "] .ErrorMessage} @ Html.LabelFor (model= > model.Email) @ Html.EditorFor (model= > model.Email) / @ if (! ViewData.ModelState.IsValid) has a problem with writing: / / the correct way to write it is @ if (! ViewData.ModelState.IsValid & & ViewData.ModelState] below "Email"] .Errors.Count > 0) {/ / get the error message from the dictionary: @ ViewData.ModelState ["Email"] .ErrorMessage [0] .ErrorMessage @ ViewData.ModelState ["Email"] .Errors [0] .ErrorMessage}

}

Then, modify the default route:

Public static void RegisterRoutes (RouteCollection routes) {routes.IgnoreRoute ("{resource} .axd / {* pathInfo}"); routes.MapRoute (name: "Default", url: "{controller} / {action} / {id}", defaults: new {controller = "Student", action = "Index", id = UrlParameter.Optional});}

After running, an error is reported. Find out the reason and modify the view code:

After running

Then verify that Name is not empty and Email enters data in an illegal format:

Finally, verify that you enter legal data:

Okay, now take a look at the second way, using data annotations for server-side validation:

Create a new class: avoid confusion

Using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Web;namespace Server_Side_Validation_IN_MVC.Models {public class StudentServer {[Required (ErrorMessage= "Name is required")] public string Name {get; set;} [Required (ErrorMessage= "email must")] [EmailAddress (ErrorMessage= "email format is incorrect")] public string Email {get; set;}

Create two new methods in the controller:

Public ActionResult SeverSideIndex () {return View ();} [HttpPost] public ActionResult SeverSideIndex (StudentServer model) {if (ModelState.IsValid) {ViewBag.Name = model.Name; ViewBag.Email = model.Email;} return View ();}

Corresponding view:

@ model Server_Side_Validation_IN_MVC.Models.StudentServer@ {Layout = null @ if (ViewData.ModelState.IsValid) {if (ViewBag.Name! = null) {Name:@ViewBag.Name Email:@ViewBag.Email}} SeverSideIndex @ using (Html.BeginForm ()) {@ Html.ValidationSummary (true) Student @ Html.LabelFor (model= > model.Name) @ Html.EditorFor (model= > model.Name) @ Html.ValidationMessageFor (model= > model.Name) @ Html.LabelFor ( Model = > model.Email) @ Html.EditorFor (model = > model.Email) @ Html.ValidationMessageFor (model = > model.Email)

}

First of all, verify that it is all empty:

Name is not empty, Email is empty

Name is not empty. Email entered illegal format data.

Both enter legitimate data:

All right, that's the server verification in MVC, and we usually use the second one for verification. That is, data annotations.

This is the end of this article on "sample analysis of ASP.NET MVC5 server verification". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report