Recently, some friends may ask some entry-level questions to sort out these questions and write them out. In previous articles, I used pure JS to write Ajax engines. In actual development, we do not like to develop them in this inefficient way. We use the Integrated MS Ajax engine, it can be a lot easier.
In MS Ajax, one way for JS to interact with C # is to call WebService, which can be ASMX or WCF. Either way, the system automatically generates a proxy JS class for the developer. The implementation method is as follows:
1. Create a website and add a WCF Service to it (select Ajax-Enabled WCF Service here), as shown in:
2. IDE will automatically generate an SVC file for us, which is an external interface and the background implementation class corresponding to this SVC. Such files will be placed under App_Code, as shown in:
3. modify the code of this class as follows:
The Code is as follows:
[ServiceContract (Namespace = "TestAjax")]
[AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. Allowed)]
Public class Service
{
[OperationContract]
Public bool ValidateUser (string uid, string pwd)
{
If (uid = "sa" & pwd = "sa ")
{
Return true;
}
Return false;
}
}
4. now we can call it on the page. First, add a ScriptManager to the page and introduce the WCF WebService we just compiled (the purpose is to generate the JS proxy class at runtime ), as follows:
The Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: ScriptManager ID = "ScriptManager1" runat = "server">
<Services>
<Asp: ServiceReference Path = "~ /Service. svc "/>
</Services>
</Asp: ScriptManager>
</Div>
</Form>
</Body>
</Html>
5. Now you can write JavaScript code to directly call the WebService written in C. The JS Code is as follows:
The Code is as follows:
<Script type = "text/javascript">
Function ValidateUser (uid, pwd ){
TestAjax. Service. ValidateUser (uid, pwd, OnSucceed, OnFailed );
}
Function OnSucceed (result ){
If (result = true ){
Window. alert ("verified ");
}
Else {
Window. alert ("Verification Failed! ");
}
}
Function OnFailed (result ){
Window. alert ("operation failed:" + result. _ message );
}
</Script>
- 2 pages in total:
- Previous Page
- 1
- 2
- Next Page