Why ajax method returning output in incorrect format in asp.net c# using jquery

Ashok Kumar 221 Reputation points
2022-12-08T13:48:41.407+00:00

I'm returning the simple json output using jQuery Ajax Method from aspx.cs page using[WebMethod] and the output is not returning properly below is my code

   using System.Web.Services;  
     
       [WebMethod]  
       public static string Chart_Symbols()  
       {  
           string myJsonResponse = "";  
     
           try  
           {  
               myJsonResponse = "[{\"symbol\":\"AARTIIND\",\"full_name\":\"NSE:AARTIIND\",\"description\":\"AARTI INDUSTRIES LTD\",\"exchange\":\"NSE\",\"ticker\":\"AARTIIND\",\"TYPE\":\"stock\"}]";  
           }  
           catch (Exception ex)  
           {  
               throw ex;  
           }  
     
           return myJsonResponse;  
     
       }  

In the above [WebMethod] I'm getting the return output like this

WebMethod Return Output

And this is my jQuery Ajax Method logic :-

   //Calling Method  
   $(document).ready(function () {  
       var res = FetchingServiceData();  
       alert(res);  
   });  
     
   //Returning output using Ajax method  
   function FetchingServiceData() {  
     
       var res = $.ajax({  
     
           type: "POST",  
           contentType: "application/json; charset=utf-8",  
           url: "TV_Chart.aspx/Chart_Symbols",  
           dataType: "json",  
           data: "{}",  
           success: function (data) { },  
           async: false,  
           error: function (err) {  
               console.log("eror is ==> "+err);  
           }  
     
       }).responseText;//.then(res => res.json()).then(symbols => {  
       //    console.log("chart_symbol :- " + JSON.parse(symbols));  
       //    return JSON.parse(symbols);  
       //});  
     
     
       //res = res.replace("{\"d\":\"[{", "[{");  
       //res = res.replace("}]\"}", "}]");  
       //res = res.replace("\\", "");  
       //res = res.replace("\\", "");  
     
       //return JSON.stringify(res);  
        //return JSON.parse(res);  
     
        return res;  
     
   }  

Once I execute the project Ajax method returning the output like this
{"d":"[{\"symbol\":\"AARTIIND\",\"full_name\":\"NSE:AARTIIND\",\"description\":\"AARTI INDUSTRIES LTD\",\"exchange\":\"NSE\",\"ticker\":\"AARTIIND\",\"TYPE\":\"stock\"}]"}
Image output:-

AjaxMthod Returning

But my output should come like this only

var res = [{ "symbol": "AARTIIND", "full_name": "NSE:AARTIIND", "description": "AARTI INDUSTRIES LTD", "exchange": "NSE", "ticker": "AARTIIND", "TYPE": "stock" }];

Why I'm not getting the correct format output in ajax method ?

Suggest me where I did the mistake.

I'm assuming this point :- [using `res = res.replace("","");' is not a good practice]

Microsoft 365 and Office Development Office JavaScript API
Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-12-09T19:10:30.23+00:00

    You can learn about generics (List<T>) in the C# programming guide.

    Learn to manage data collections using List<T> in C#

    As stated, the aspx [WebMethod] as returns JSON data as {"d": {object}}. This is not consistent with modern REST APIs.

    Example

    Markup

    <div>  
        <asp:Button ID="AjaxPost" runat="server" Text="AJAX" />  
    </div>  
    <div>  
        <table id="ticker-table" border="1">  
            <thead>  
                <tr>  
                    <th>symbol</th>  
                    <th>description</th>  
                    <th>exchange</th>  
                    <th>full_name</th>  
                    <th>ticker</th>  
                    <th>TYPE</th>  
                </tr>  
            </thead>  
            <tbody>  
            </tbody>  
        </table>  
    </div>  
    

    JavaScript/jQuery

    $("#<%=AjaxPost.ClientID%>").on('click', function (e) {  
        e.preventDefault();  
      
        var data = {  
        };  
      
        $.ajax({  
            type: "POST",  
            contentType: "application/json",  
            url: "WebForm1.aspx/Chart_Symbols",  
            data: JSON.stringify(data),  
        })  
            .done(function (data) {  
                console.log("success");  
                console.log(data);  
                $('#ticker-table tbody tr').remove();  
                var html = '';  
                for (var i = 0; i < data.d.length; i++)  
                    html += '<tr>' +  
                        '<td>' + data.d[i].symbol + '</td>' +  
                        '<td>' + data.d[i].description + '</td >' +  
                        '<td>' + data.d[i].exchange + '</td >' +  
                        '<td>' + data.d[i].full_name + '</td >' +  
                        '<td>' + data.d[i].ticker + '</td >' +  
                        '<td>' + data.d[i].TYPE + '</td >' +  
                        '</tr>';  
                $('#ticker-table tbody').append(html);  
            })  
            .fail(function (jqXHR, textStatus, c) {  
                console.log("failure");  
                console.log(textStatus);  
            });  
    });  
    

    Web Method

        public partial class WebForm1 : System.Web.UI.Page  
        {  
            protected void Page_Load(object sender, EventArgs e)  
            {  
      
            }  
      
            [WebMethod]  
            public static List<ChartSymbolsModel> Chart_Symbols()  
            {  
                List<ChartSymbolsModel> model = PopulateData();  
                return model;  
            }  
      
            private static List<ChartSymbolsModel> PopulateData()  
            {  
                return new List<ChartSymbolsModel>()  
                {  
                    new ChartSymbolsModel()  
                    {  
                        symbol = "SPX",  
                        description = "S&P 500",  
                        exchange = "NASDAC",  
                        full_name = "NASDAC",  
                        ticker = "3961",  
                        TYPE = "Index"  
                    },  
                    new ChartSymbolsModel()  
                    {  
                        symbol = "Foo",  
                        description = "BAR",  
                        exchange = "NASDAC",  
                        full_name = "NASDAC",  
                        ticker = "8523",  
                        TYPE = "Stock"  
                    }  
                };  
            }  
        }  
      
        public class ChartSymbolsModel  
        {  
            public string symbol { get; set; }  
            public string full_name { get; set; }  
            public string description { get; set; }  
            public string exchange { get; set; }  
            public string ticker { get; set; }  
            public string TYPE { get; set; }  
        }  
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-12-08T15:11:02.333+00:00

    Page level web method serialization return data as {"d": {object}}.

    The debug screenshot is testing the myJsonResponse content within the Web Method body before the framework serialized the string. The AJAX response shows the actual JSON format returned from the web method.

    A few other points, the design serializes an already serialized JSON string. The results should have the following shape without double quotes around the collection []. Otherwise, your client code has to deserialize the response twice.

    {  
        "d":[{  
            "symbol":"AARTIIND",  
            "full_name":"NSE:AARTIIND",  
            "description":"AARTI INDUSTRIES LTD",  
            "exchange":"NSE",  
            "ticker":"AARTIIND",  
            "TYPE":"stock"  
          }  
        ]  
    }  
    

    The Web Method should return a List<T> not a string.

    [WebMethod]  
    public List<MyJsonResponse> string Chart_Symbols()  
    

    Model

        public class MyJsonResponse  
        {  
            public string symbol { get; set; }  
            public string full_name { get; set; }  
            public string description { get; set; }  
            public string exchange { get; set; }  
            public string ticker { get; set; }  
            public string TYPE { get; set; }  
        }  
    

  2. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2022-12-09T07:47:38.547+00:00

    Hi @Ashok Kumar ,
    I think you can use response.d directly to get your data.

     var res = $.ajax({  
                    type: "POST",  
                    contentType: "application/json; charset=utf-8",  
                    url: "WebForm3.aspx/Chart_Symbols",  
                    dataType: "json",  
                    data: "{}",  
                    success: function (response) {  
                        alert(response.d);  
                    },  
                    async: false,  
                    error: function (err) {  
                        console.log("eror is ==> " + err);  
                    }  
                });  
    

    268881-image.png
    268829-image.png
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.