ASP. NET mvc3 provides a remote server call mechanism that can be used to verify the validity of a field in form without submitting the entire form to the server. When a field cannot be verified by the client and may fail to be verified after it is submitted to the server, you can use the remote server call mechanism. For example, some websites require users to register a unique user name.
The following is a simple example of using the remote server call mechanism to verify whether the user name is repeated.
1. Create an empty mvc3 project named mvcremotevalidation
2. Resource Manager, models folder, right-click, add class, and name it user
Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. MVC; using system. componentmodel. dataannotations; namespace mvcremotevalidation. models {public class user {[required (errormessage = "name cannot be blank")] public string name {Get; Set ;}}}
3. In resource manager, right-click controllers and add a controller named homecontroller, as shown in:
4. Add the action method isunique_available (string name) to homecontroller to check whether the name already exists,CodeAs follows:
Public jsonresult isunique_available (string name) {list <user> Users = userservice. getusers (); users = users. where (u => U. name = Name ). tolist (); If (users. count = 0) return JSON (true, jsonrequestbehavior. allowget); string suggesteduid = string. format (cultureinfo. invariantculture, "{0} already exists. ", Name); Return JSON (suggesteduid, jsonrequestbehavior. allowget );}
Note: This action method can be placed in any controller with no restrictions.
5. Add attribute to the name attribute of the class user
Public class user {[required (errormessage = "name cannot be blank")] [Remote ("isunique_available", "home")] public string name {Get; set ;}}
Specifies the remote attribute of name, and specifies the action method to be called to execute this verification, and the Controller of this action
5. Press F5 to run
The index page is as follows:
The user names Tom and marry already exist.
6. Click the create new link to open the new window:
To view the HTML source file, data-Val-remote-additionalfields = "*. name "and data-Val-remote-url ="/home/isunique_available "attributes, "/home/isunique_available" is the controller and action specified by remote added for the name attribute in the user class.
7. In the input box, enter "Tom", and a message is displayed, indicating that "Tom" already exists.
8. Source Code link: mvcremotevalidation.rar