Send AJAX request to .aspx page and return JSON

I know that it is possible to send an AJAX request to an .asmx page. And I also know that an .asmx page handles an AJAX request via a web method.

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can define web methods in the code-behind of your .aspx page and then call them:

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

And then, to call a 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.

Method 2

if i understood question correctly, Aspx is same as HTML. It will be rendered as HTML. but only difference is Server Side and Controls retaining the states with state mechanism.

so you can do jquery $.ajax() function.

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

or if you want to write out json value to the response, then use Response.ContentType
first use any Javascript serializer(JSON.NET) , then set the contentType like this.

Response.ContentType="application/json";

Method 3

 $.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 above code


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x