Passing HTML back inside a JSON object

Posted on

Problem

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).

Solution

I would consider returning with a more detailed JSON object:

{
    errorMessage: "things have gone wrong!",
    data: [
        {
            link: #,
            linkText: Test,
            size: 0MB
        },
        {
            link: #,
            linkText: Test2,
            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!",
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *