asp.net MVC5 Verification series of remote Validation_ practical skills

Source: Internet
Author: User
Tags min static class

Most developers may encounter situations where it is necessary to check whether a user with the same name already exists in the database before creating the user. In other words, we want to make sure that there is only one user name in the program that cannot be duplicated. It is believed that most people have different solutions, but ASP.net MVC provides us with a feature, the remote Validation, that can solve similar problems.

Remote validation called an AJAX request, either get or post, and then invoke the method, which must have at least one argument, and the return type of the method is JSON-formatted. "MVC through the Jsonresult to do", this method is the parameter of the entity to verify the attributes "must, otherwise cannot verify, the case of the argument does not matter." "If this validated method returns a value of true, then the same user exists for the table name, and we return false to the foreground page. Indicates that validation does not pass.

All right, let's get to the point!
First create a blank MVC project, and under the Model folder, create a new class RemoteUser:

public class RemoteUser
 {public 
 string Name {get; set;} 
 public string Email {get; set;}
 
 }

Then build a test data class:

 public static class Myremotestaticdata
 {public
 static list<remoteuser> remotelist
 {
 get
 { return
 new list<remoteuser> ()
 {
 new RemoteUser () {name= "Daniel", email= "Daniel@163.com"},
 new RemoteUser () {name= "CFS", email= "CFS@163.com" "}
 };
 }

 }
 }

In a new controller Myremotecontroller "primarily for Remote Authentication":

Using SERVER_SIDE_VALIDATION_IN_MVC. Staticdata;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;

Namespace Server_side_validation_in_mvc. Controllers
{public
 class Myremotecontroller:controller
 {
 //get:myremote public
 Jsonresult Remotevalidate (string name)//The name of the argument here must be the same as the name of the text box control in the view, but it doesn't matter
 {
 //If there is a username, that is, isexists=true
 bool isexists = myremotestaticdata.remotelist.
 Where (S => s.name.tolowerinvariant ().
  Equals (name. ToLower ())). FirstOrDefault ()!= null;
 Returns false to the foreground indicating that there is already a username return
 Json (!isexists,jsonrequestbehavior.allowget);
 }

 

 


After adding the validation above, we'll revise the model entity:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;

Namespace Server_side_validation_in_mvc. Models
{public
 class RemoteUser
 {
 [Remote ("Remotevalidate", "myremote", errormessage = "Sorry, username already exists!") Please re-enter!!! ")] public
 , string Name {get; Set Public

 
 string Email {get; set;}}

 
 }


Then in the new controller to create a test:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;

Namespace Server_side_validation_in_mvc. Controllers
{public
 class Usercontroller:controller
 {public
 

 actionresult Addremoteuser ()
 {return
 View ();
 }
 }
}

Add Addremoteuser view, " note here, Remote validation is the need to introduce jquery Plug-ins and enable client-side authentication"

This is the introduction of the script library, and is mainly used to introduce jquery plug-ins.

@model Server_side_validation_in_mvc.

Models.remoteuser @{viewbag.title = "Addremoteuser";}  

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 = "User", action = "Addremoteuser", id = urlparameter.optional}
 );
 

To run the project:

Enter test data: CFS, press the TAB key, automatically validated.

Here we have a remote verification of the name field, now I want to verify the email field, need to use the additionalfields, attributes, and also need to add another authentication method:

Using SERVER_SIDE_VALIDATION_IN_MVC.
Staticdata;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Using SYSTEM.WEB.MVC; Namespace Server_side_validation_in_mvc. Controllers {public class Myremotecontroller:controller {//Get:myremote public Jsonresult remotevalidate (string
 Name//The parameter names here must be the same as the name of the text box control in the view, but the case does not matter {//If there is a username, that is, isexists=true bool isexists = myremotestaticdata.remotelist.
  Where (S => s.name.tolowerinvariant (). Equals (name. ToLower ())).
 FirstOrDefault ()!= null;
 Returns false to the foreground, indicating that username return Json (!isexists,jsonrequestbehavior.allowget) already exists; Public Jsonresult remotevalidationaddtional (string name, string email) {//If a user name exists, that is isexists=true bool isexists =
  Myremotestaticdata.remotelist. Where (S => s.name.tolowerinvariant (). Equals (name. ToLower ()) && s.email.tolowerinvariant (). Equals (email. ToLower ())).
 FirstOrDefault ()!= null; Returns false to the foreground indicating that there is already a username return Json (!isexists, Jsonrequestbehavior).Allowget);

 }
 }
}

then modify the corresponding entity class:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;

Namespace Server_side_validation_in_mvc. Models
{public
 class RemoteUser
 {
 [Remote ("Remotevalidate", "myremote", errormessage = "Sorry, username already exists!") Please re-enter!!! ")] public
 , string Name {get; Set

 /Note that the additionalfields= "name" Here, the Name field must be exactly the same as the field in Modle
 [Remote ("Remotevalidationaddtional", " Myremote ", Additionalfields =" Name ", errormessage =" Sorry email already exists! " Please re-enter!!! ")] public
 string, Email {get; Set }

 } 
 }

Then run the project:

Enter the test data written in the test class:

Here we have a remote validation for two fields.
The Additionalfields validation field is used above, and if we want to validate more than one field, we can add it in addtionalfiled, separated by commas.

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.