Use Ajax to call the C # function in the background in javascript,
Recently, a website project has been followed. The UserName requirements for user tables in the database are unique. Therefore, when you select a user name for registration, you must first check whether the user name is occupied, and give a prompt. The initial implementation is: after the user fills out the registry form and submits it, the user verifies it in the background. However, many websites are designed to provide prompt immediately after the user fills in the user name and the TextBox loses focus, for example, https://passport.csdn.net/account/register. the response is fast and should be checked in the frontend. It took some time today to look up some information on this point.
When js calls the background C # function to detect the user name, it needs to obtain the user name entered by the user, and then check whether the database contains the User Name:
Some (http://www.cnblogs.com/morningwang/archive/2008/04/07/1140340.html) use the following method:
// Background
Protected string CsharpVoid (string strCC)
{
StrCC = "Hello! "+ StrCC;
Return strCC;
}
// Front-end
Function Init ()
{
Var v = "China ";
Var s = '<% = CsharpVoid ("' + v + '") %> ';
Alert (s );
}
I tried and the result was not as expected. Later, I decided to use Ajax for implementation. Since we have little knowledge before, we have taken a lot of detours throughout the process. Fortunately, we have finally made some mistakes. The specific implementation steps are as follows:
1. Add reference under the bin directory: AjaxPro.2.dll
Add using AjaxPro to the background Codefile;
2. Add the following content under <Add name = "AjaxPro" verb = "POST, GET" path = "ajaxpro/*. ashx" type = "AjaxPro. AjaxHandlerFactory, AjaxPro.2"/>
3. Add <asp: ScriptManager> and EnablePageMethods = "true" in the aspx file of Site. master ".
4. Usage:
1) Add before the class: [AjaxNamespace ("ANSP")] (modify the namespace name, which can be skipped)
[AjaxNamespace ("ANSP")]
Public partial class Physician_WUC_PhysicianInfor: System. Web. UI. UserControl
{
}
2) Page_Load
Protected void Page_Load (object sender, EventArgs e)
{
Lca_dataservice = new lca_database_service.lca_database_service ();
Utility. RegisterTypeForAjax (typeof (Physician_WUC_PhysicianInfor ));
}
3) add [AjaxPro. AjaxMethod] before the method to be called.
[AjaxPro. AjaxMethod]
Public bool CheckUsernameExist (string username)
{
Bool NotExist = false;
Try
{
System. Data. DataSet ds = lca_dataservice.readDoctor (username );
If (ds = null | ds. Tables [0]. Rows. Count <= 0)
{
NotExist = true;
}
}
Catch (Exception ex)
{
NotExist = false;
}
Return NotExist;
}
4) frontend js call method:
Var Exist = ANSP. CheckUsernameExist (userName). value;
Exist is the return value of the function.
If (Exist = true)
{
// The user name does not exist.
} Else
{
// The user name exists.
}
After the above settings, the requirements are met.