views:

139

answers:

2

I'm using ASP.NET-MVC and returning JSON or HTML from my MVC actions.

I've come across some cases where I need to return BOTH JSON and HTML at the same time. For instance I may update a shopping cart and need to return an HTML representation as well as an updated JS object model.

I've found a lot of questions on SO about when to return which type of response, but none talking about how to return both.

Is there a reliable way of doing this? Must work across browsers without any extra thought.

  • multi-part response?
  • HTML encoded in the JSON result?
  • some kind of script tag embedded in the HTML containing JSON that would run a function to update the object model. i'm leaning towards this method, but concerned that scripts may not reliably be run when adding them to the DOM with html("...")
  • some other way?

If theres not a good way I'll just have to make 2 requests to get the HTML and then the JSON.

+1  A: 

To return a multipart body, you could pack the response inside a MIME container. But that would make the response unusable by most clients.

I usually put html inside the JSON result.

Patonza
thanks - any tricks to decoding/encoding it to be JSON friendly? any if by any chance you're using ASP.NET MVC how did you actually get the HTML from a view into the JSON model
Simon_Weaver
Clientside I use jQuery wrappers for JSON.Serverside, all you need to encode HTML into JSON strings is to escape quote characters (if you're using UTF charset).As for the .NET MVC, I guess you should directly call the Render() method passing a memory-based HtmlTextWriter, then you use the html stored in the buffer.
Patonza
+2  A: 
an HTML representation as well as an updated JS object model

If you are using HTML and JS to update the same portion of the view, then consider HTML encoded in the JSON result. If you are trying to update different portions of the view, then I will use two action methods to follow "single responsibility" rule.

J.W.