79

In my particular situation, I have a couple of solutions to my problem. I want to find out which one is more feasible. In this case, I can also achieve my goal by returning a JSON object from my server side code; however, I do not know how it is done and what the best way of doing it is.

First off, I don't need a full aspx page as I only need a response returned from code. So, do I use web services, a handler, or is there any other specific way to do this?

Is this solution feasible? Do I build the JSON string using the StringBuilder class and inject that string into the target aspx page? Are there any precautions or things that I should be aware of?

I appreciate your ideas.

------------UPDATE !------------

Suppose I have a JSON object in my userlist.aspx page, which then I use with jQuery...

{"menu": { "id": "color1", "value": "color", "popup": { "menuitem": [ {"value": "Red"}, {"value": "Green"}, {"value": "Yellow"} ] } }} // example taken from the json.org/example page 

Now when I want to add a new menu items from my aspx page, what do I do... I think this way my question is more specific...

Lets assume I create a new string in my aspx code, as such "{"value": "Blue"}. How do I inject this into the already existing itemlist in the target page? Or is this not the correct approach to this kind of situation? If not, how else can it be achieved?

Also, if I wanted to fire a jQuery event when a new item is added to this list, how is this achieved?

------------UPDATE 2 on 26 August 2015 ------------

By the time I asked this question, the way I was approaching the problem was in another aspect. I am now more proficient in the subject and can gladly accept the most voted answer since the approach to this question clearly should not include the already existing JSON and output a new one from the code as @DavGarcia also suggests.

4 Answers 4

143

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}"; Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(json); Response.End(); 

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

Sign up to request clarification or add additional context in comments.

6 Comments

Updated answer to include Response.End(), otherwise page controls may be rendered
One of the issue we have faced with such approach is - If your page is complex and has multiple user controls and suppose one of your page checks for a cookie and if it isn't present, tries to set it. This will always error out throwing 'Server cannot modify cookies after HTTP headers have been sent' error.
when i use Response.End(); in my code it result to an error : {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} ThreadAbortException error
@davgarcia thats a good answer but when im using it, my previous page gets removed from the history (if i use the back button i cant return)
@SoliQuid I'm a bit confused, you don't want to have the browser navigate to the page returning JSON. The call to that page should be happening somewhere in the client side code, such as in a jQuery .getJSON or .ajax call. Neither should affect the browser history.
|
22

no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.

The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.

edit:

here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:

public ActionResult GetData() { var data = new { Name="kevin", Age=40 }; return Json(data, JsonRequestBehavior.AllowGet); } 

This return data could be called via JQuery as an ajax call thusly:

$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); }); 

2 Comments

thanks for the answer, I am not using MVC but will get into research starting from your answer. While I do that, can you provide me some resources you already know, if any?
Cool! simplest solution
13

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new { orientation = Cache["orientation"], alerted = Cache["alerted"] as bool?, since = Cache["since"] as DateTime? }); Response.Write(json); 

2 Comments

I had to look this up, so incase anyone else doesn't know, that Json object is System.Web.Helpers.Json -- If you don't reference that DLL already, or can't, you can use System.Web.Script.Serialization.JavaScriptSerializer, which works about the same.
@Scott - if you were looping through a recordset on a single ASP.net page how would you group them (rather than individual like they are in your example)?
4

If you get code behind, use some like this

 MyCustomObject myObject = new MyCustomObject(); myObject.name='try'; //OBJECT -> JSON var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string myObjectJson = javaScriptSerializer.Serialize(myObject); //return JSON Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(myObjectJson ); Response.End(); 

So you return a json object serialized with all attributes of MyCustomObject.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.