asp.net MVC5 Verification series of service-side validation _ Practical Tips

Source: Internet
Author: User
Tags create index

This article, I will say, uses the data annotation API for server-side validation. The ASP.net MVC framework, when executed, validates all data passed to the controller, fills the error message into the Modelstate object if the validation fails, and passes the object to the controller, and then the method in the controller is judged by the state of the modelstate. Whether to verify the failure or verify the pass.

Here, I will use two methods to verify the legality of the data, one is to manually add error messages to the Modelstate object, and the other is to do it using the data annotation Annotation API.

Let's take a look at how to use manual validation:

We 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;

  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 () {retur
  n View ();
   [HttpPost] public actionresult Index (Student model) {//server-side authentication, method one, manually add error message to Modelstate object///if name is empty if (string. IsNullOrEmpty (model.
   Name)) {modelstate.addmodelerror ("name", "name is required"); //If the email is empty if (string. IsNullOrEmpty (model.
   email)) {modelstate.addmodelerror ("email", "email is required"); else {string Emailregex = @ "^" ([a-za-z0-9_\-\.] +) @ (\[[0-9]{1,3} "+ @" \. [0-9] {1,3}\. [0-9] {1,3}\.) | ([a-za-z0-9\-]+\ "+ @".) +)) ([a-za-z]{2,4}| [0-9] {1,3}) (\]?)
    $";
    Regex re = new regex (Emailregex); When the email is not empty, the format is not valid if (!re). IsMatch(model.
    email)) {modelstate.addmodelerror ("email", "email is not valid"); }//entity validation through if (modelstate.isvalid) {viewbag.name = model.
    Name; Viewbag.email = model.
   Email;
  return View (model);

 }
 }
}

Create INDEX view:  

@model Server_side_validation_in_mvc.

models.student @{Layout = null;} <! DOCTYPE html>  

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, the error is not correct. Looked for the reason, modified the View code:

After running,

Next verify that name is not empty, email input illegal format data:

Finally verify, enter the valid data:

Okay, now 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= "e-mail must be")]
  [EmailAddress (errormessage= "e-mail format is not")] public
  string Email { Get Set }
 }
}

Create a new two method 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 ();

  }

The corresponding view:

@model Server_side_validation_in_mvc.
  Models.studentserver @{Layout = null;} @if (ViewData.ModelState.IsValid) {if (viewbag.name!= null) {<b> Name: @ViewBag. name<br/> Email: @ViewBag. Email </b>}} <! DOCTYPE html>  
 

First verify that all is empty:

Name is not empty, email is empty

Name is not empty, email input illegal format data

All two enter the valid data:

Well, the above is the service-side validation in MVC, and we typically use the second one to validate. Which is the data annotation.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.