# Passing HTML back inside a JSON object

I'm working on a piece of code in my MVC3 application and I'm struggling to decide if what I plan to do is a bad idea or not.

I have a snippet of JavaScript that calls an MVC action that in turn returns an HTML partial that I then insert into a div element on my page. Nothing complicated there.

However, things have changed and I now need to pass back a possible error message as well. I propose to send this back with the HTML partial as part of a JSON object.

It would look something like this:

{
errorMessage: "things have gone wrong!",
partial : "<tr><td><a href='#'>Test</a></td><td>0MB</td></tr><tr><td><a href='#'>Test2</a></td><td>1MB</td></tr>"
}


This seems pragmatic but maybe a little dirty to me, so I'd like the thoughts of the community, please.

Now the obvious alternative would be to pass the table data back as JSON as well, and parse it client-side. But this will be a pain, even with something like jQuery templates (the example I've put up is simplified).

• Would you please clarify the reason why you want to post back the partial html to the server side (if I understand correctly)? Also, what would possibly cause the erros on the client side? What kind of processing is happening there? Just trying to get a clearer picture. – Anas Karkoukli Nov 23 '11 at 17:44
• A misunderstanding. The json object is being passed to the client side. Am literally just passingly a HTML table and an error message back to the client – mjmcloug Nov 23 '11 at 19:12

I would consider returning with a more detailed JSON object:

{
errorMessage: "things have gone wrong!",
data: [
{
size: 0MB
},
{
size: 1MB
}
}


It moves some processing from the server to the clients but it's more reusable. For example you need a second type of table later with the same data but with an extra column. With this JSON format you don't have to touch the server side code nor to parse and modify the returned HTML on the client side.

Finally, if there is an error maybe you want to omit the whole data part:

{
errorMessage: "things have gone wrong!",
}

• i suggest to come back with an additional template, eg: { errorMessage: "..", data: [ ... ], template: '<div>... </div>' } It allows default decorating the data – Jarod DY Law Nov 24 '11 at 8:08

Passing the HTML is a bad idea because it will cause a tight coupling. It will be difficult for you to port it to a mobile application. Pass the data as JSON as suggested by palacsint, the consumer should know the format so that it can parse it

• I think one only asks for advice when they already know the answer. They just don't like it :D – mjmcloug Nov 24 '11 at 9:08
• or when one is really confused – NRS Nov 24 '11 at 10:38