Calling Page Method
Today I will tell you how to call a page method using ajax request.
AjaxRequest.aspx
<script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#btnGetData").click(function()
{
$.ajax({
type: "POST",
url: "AjaxRequest.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#GetData").append(msg.d);
}
});
});
});
</script>
<div id="Data">
To get data using ajax request click on this button.<br />
<input type="button" id="btnGetData" value="Get Data" />
<div id="GetData">
</div>
</div>
AjaxRequest.aspx.cs
[System.Web.Services.WebMethod]
public static string GetData()
{
string query = "select * from employee";
DataTable dt = new DataTable();
DataAccess da = new DataAccess();
da.FillGrid(dt, query);
string table = "<table><tr><td>This data is returned using ajax call.</td></tr>";
table += "<tr><td>Id</td><td>Name</td></tr>";
foreach (DataRow dr in dt.Rows)
{
table += "<tr><td>" + dr[0].ToString() + "</td><td>"+dr[1].ToString()+"</td></tr>";
}
table += "</table>";
return table;
}
Now let’s discuss in detail.$.ajax has some parameters I will discuss only some important things in it.
· URL :This is the url of your web page and after that comes your method name.i-e mypage.aspx/mymethod.
· Data: if your method accepts some arguments you need to pass them here and argument name must be same as in the method. i-e suppose you have a method which accepts an argument public static string GetName(string name) so when you will call it you will pass it like data: "{name:'"+somename+"'}".
· Success: When your method is called successfully you can write code here what you want after success. You can call another function in it.
· The method in cs class should be webmethod and should be static.
Now in this example I have a query which returns data and I have created an HTML table using data retrieved from database and returned that data and in my page I have appended this data to a div.
Comments
Post a Comment