Sudha
Sudha

Reputation: 2108

Ajax response data in .net

I have a asp .net web page and a button in it. I'm calling an ajax method in the button click event as follows

 $("#btnTest").click(function () {
                 $.ajax({
                     type: 'POST',
                     url: 'test2.aspx',
                     success: function (data) {
                         alert( data);

                     },
                     error: function (data) {
                         alert("In error  ");

                     }
                 });
             });

In success part alert( data) Im getting the html code of the page test2.aspx (which one I have given in ajax url).

In test2.aspx.cs code is given as below

protected void Page_Load(object sender, EventArgs e)
    {
        jsonTest();
    }

    public List<string> jsonTest()
    {
        List<string> list = new List<string>();
        list.Add("aa");
        list.Add("bb");
        list.Add("cc");
        return list;        
    }

Why this data in 'list' is not coming as response data in ajax?

Upvotes: 6

Views: 8648

Answers (4)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Try Response.Write() method for that purpose

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write("data to be returned");
}

Or try to write static webmethods in aspx page. Those methods can be call from ajax

Upvotes: 5

Sampath Baddipudi
Sampath Baddipudi

Reputation: 1

Use like this..

 $("#btnTest").click(function () {
                 $.ajax({
                     type: 'POST',
                     url: 'test2.aspx',
                     success: function (data) {
                         alert( data.d[0]);
                         alert( data.d[1]);
                         alert( data.d[2]);

                     },
                     error: function (data) {
                         alert("In error  ");

                     }
                 });
             });

Upvotes: 0

mmpatel009
mmpatel009

Reputation: 941

You cannot return data from aspx to ajax. try this

HttpContext.Current.Response.Write(list);
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.SuppressContent = true;

This will help to solve your problem.

Upvotes: 2

शेखर
शेखर

Reputation: 17614

You can't call a normal page method from jQuery.
You need to create a web-method to access that from jQuery.
Here is a good link regarding how to call a page method
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Upvotes: 1

Related Questions