0

I am working on a basic ASP.NET & AJAX/JSON assignment and I am frustrated with making it work. One of the requirements was to create an AJAX/JSON method to do some manipulations on SQL DB data.

In order to complete that, I used the following code:

In the aspx:

    $.ajax({
              type: "GET",
              dataType: "json",
              url: "Retrieve",     
              success: function (data) {
                  alert(data);
                  var col;
                  for (col in data) {
                      alert(col);
                      addRow(data[col].id, data[col].Name, data[col].catagory, data[col].difficulty, data[col].company, data[col].price, '#products');
                  }
              },
              error: function () {
                  alert("1");

              }

In the "retrieve.aspx" page (the part of code that creates the data for JSON):

    Response.ContentType = "application/json; charset=utf-8";
            bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            string category = Request.QueryString["category"];
            //string a = JsonConvert.SerializeObject(getProducts(category));
            var a = getProducts(category);
            // instantiate a serializer
            JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

            var TheJson = TheSerializer.Serialize(a);
            Response.Write(TheJson);

And last but not least, if i try to change the dataType to text, it will show that the content is the JSON-structured text together with an HTML page code.

What am I missing here?

Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35

1 Answers1

1

You need to make sure ASP.NET does not render anything else outside of the json content you put into the response. To do so, clear the response beforehand:

Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
...

and in the end complete the response right away:

Response.Write(TheJson);
HttpContext.Current.ApplicationInstance.CompleteRequest();

See this excellent answer as to why CompleteRequest should be used here instead of more widespread Request.End().

However using pages to output JSON seems like an overhead. You may want to checkout simpler ways of doing the same, which is Http Handlers. Plenty examples over the internet, here is one

Community
  • 1
  • 1
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • `Response.End` is usually a bad workaround for a problem that can be fixed in some other fashion. It hard ends the request by internally doing a thread abort. Even [the documentation](https://msdn.microsoft.com/en-us/library/system.web.httpresponse.end(v=vs.110).aspx) says: _"This method is provided only for compatibility with ASP"_ – James Thorpe Jun 14 '16 at 13:10
  • 1
    @JamesThorpe, indeed, thanks for pointing out. Researched a bit and learned a lot, updated answer with a better option – Andrei Jun 14 '16 at 13:15