Send an AJAX request to the .aspx page and return the JSON

I know that you can send an AJAX request to a page .asmx. And I also know that the page .asmxprocesses the AJAX request using a web method.

Can I also send an AJAX request to a page .aspx? If so, does the page .aspxalso handle the AJAX request via the web method? Please note that I would like to return a JSON response from the page .aspx. Is it possible?

+5
source share
3 answers

You can define web methods in the code for your page .aspx, and then call them:

[WebMethod]
public static string doSomething(int id)
{
    ...
    return "hello";
}

And then to call the web method in your jQuery code:

$.ajax({
    type: "POST",
    url: "YourPage.aspx/doSomething",
    data: "{'id':'1'}",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        var returnedstring = data.d;
        var jsondata = $.parseJSON(data.d);//if you want your data in json
    }
});

Here is a good link to get started.

+8

, Aspx , HTML. HTML. - Side Server Controls, .

jquery $.ajax().

$.ajax({
     url: UrlToGetData,
     dataType:'json',
     success:function(data){
             //do some thing with data. 
           }
});

json , Response.ContentType Javascript- (JSON.NET), contentType .

Response.ContentType="application/json";
+2
 $.ajax({
            url: "(aspx page name/method to be called from the aspx.cs page)",
            type: "POST",
            dataType: "json",
            data: $.toJSON(jsonData),
            contentType: "application/json; charset=utf-8",
            success: function (data, textStatus, jqXHR) {
                 //TO DO after success
        }
});

Try the code above

+1
source

All Articles