One day I thought, how convenient it would have been if I could call a server method from my client script on my web page, simply, as I can call a javascript method from another javascript method.
And yes, there is the asp.net WebMethod attribute with which we can do a sever method calling as calling a method locally. WebMethod with JQuery and a little bit of JSON and we are done.
Here is the code snippet to implement the same:
return "Hi " + name;
}
WebMethod attribute requires reference to System.Web.Services.
And remember to mark the method static, otherwise it will not work.
{
$.ajax({ type:"post",
url: "Default.aspx/ServerMethod",
data: JSON.stringify({name:"Boraska"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hurreyyy! I got " + data.d + "from server method.");
}
});}
This small script and WebMethod attribute do the fantastic job, no need to go in detail of page life-cycle events and many more things.
Now, here again, there are few things that needs to be taken care to make this work:
And yes, there is the asp.net WebMethod attribute with which we can do a sever method calling as calling a method locally. WebMethod with JQuery and a little bit of JSON and we are done.
Here is the code snippet to implement the same:
Asp.Net Code
[WebMethod]
public static string ServerMethod(string name)
{ return "Hi " + name;
}
WebMethod attribute requires reference to System.Web.Services.
And remember to mark the method static, otherwise it will not work.
Client Script
function GetResultFromServer(){
$.ajax({ type:"post",
url: "Default.aspx/ServerMethod",
data: JSON.stringify({name:"Boraska"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hurreyyy! I got " + data.d + "from server method.");
}
});}
Now, here again, there are few things that needs to be taken care to make this work:
- Url contains the method name which you want to call. Specify the url carefully. If you need you can pass query strings as well with url.
- Data is the parameters you want to pass to the server method. The name and number of parameters must match to the server method what you are passing from here.
- More than one parameters can be passed to the method but their types should be compatible, I mean you can pass "abc" to object type parameter but not to int type of parameter in the server method.