JQuery Postback with Webforms
We are redesigning the main part of our website and instead of using a 90KB AJAX file, I would rather use a jQuery 1900 script.
I've seen the following articles:
- Using jQuery for AJAX with ASP.NET WebForms
- jQuery autocomplete in ASP.NET web forms?
- Autocomplete with ASP.Net MVC and JQuery
The thing I am not getting is how to do the postback for a specific method, either in code or in another class.
I know in ASP.NET-MVC I can post back to a controller / action. How can I call a specific method in WebForms?
Something along the lines; $ .post ("class and action", (parameter: value} ......
Any thoughts, code, etc.
+2
source to share
1 answer
It is very easy to call certain encoded methods. Here's a nice article with all of Dave's details.
Just declare the method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
-
WebMethod
must be on a static method - Be sure to line the posted data when sending anything (i.e.
JSON.stringify(yourDataObject)
) will deserialize according to the method parameters -
msg
- the answer, the return result of your method is in the propertymsg.d
+4
source to share