Using jquery's $.ajax () makes it easy to invoke the ASP.net background method.
Let's start with a simple example warm up.
1 , parameter-free method calls
C # Background code:
1
2 using System.Web.Services;
3 [WebMethod]
4 public static string Sayhi ()
5 {
6 return "hi,welcome to china!";
7}
8
Note: 1. Methods must be static and have [WebMethod] declarations.
HTML code:
< div >
< Asp:button ID = "Btnclick" runat = "server" Text = "click me"/>
< br/>
< span id = "MSG" ></span >
</div >
jquery Code:
Code
< script type = "Text/javascript" >
$ (document). Ready (
function () {
$ ("#btnClick"). Bind ("click", Function () {
$.ajax ({
Type: "Post",
URL: "Ajaxhandler.aspx/sayhi",
ContentType: "Application/json; Charset=utf-8 ",
DataType: "JSON",
Success:function (data) {
$ ("#msg"). CSS ("Color", "#0000FF"). HTML (DATA.D);
},
Error:function (Err) {
$ ("#msg"). CSS ("Color", "#FF0000"). HTML ("Access Faield:" + err);
}
});
return false;
});
});
</script >
Run Result:
The data format returned by JSON is clearly visible through the firebug, so it is DATA.D when fetching the data.
2. Method calls with Parameters
C # Background code:
HTML code:
Code
< div >
< Asp:button ID = "Btnclick" runat = "server" Text = "click me"/>
Address: < Asp:textbox ID = "txtaddress" runat = "server" ></asp:textbox >
Family name: < Asp:textbox ID = "txtname" runat = "server" ></asp:textbox >
< br/>
< span id = "MSG" ></span >
</div >
jquery Code:
Code
< script type = "Text/javascript" >
$ (document). Ready (
function () {
$ ("#btnClick"). Bind ("click", Function () {
var add = $ ("#txtAddress"). Val ();
var txtname = $ ("#txtName"). Val ();
$.ajax ({
Type: "Post",
URL: "Ajaxhandler.aspx/sayhi",
Data: "{' Address ': '" + add + "', ' name ': ' + txtname +" '} ",
ContentType: "Application/json; Charset=utf-8 ",
DataType: "JSON",
Success:function (data) {
$ ("#msg"). CSS ("Color", "#0000FF"). HTML (DATA.D);
},
Error:function (Err) {
$ ("#msg"). CSS ("Color", "#FF0000"). HTML ("Access Faield:" + err);
}
});
return false;
});
});
</script >
Run Result:
3 , returns a call to the list collection method
C # Background code:
[WebMethod]
public static string Sayhi (string address, string name)
{
Return "Hi," + address + "" + Name;
}
Code
[WebMethod]
public static List < string > sayhi (string Address, string name)
{
List < string > list = new List < string > ();
for (