Monday, November 1, 2010

How to return HTML in JSON Response using ASP.NET and jQuery

During the development of my recent project (Delight), I ran into a challenge that normally I wouldn’t believe will take me any time more than what's required to code it straight up.

Because of the heavy use of ajax in the application, I wrote a generic jquery function to handle all ajax request triggered by a particular group of controls or elements, it was very useful and a time saver for me. In most cases, the JSON is returned in this format:

{Successful: "true", Message : "response message", Data  : "object or html"}

The interesting part of this response is the "Data" part, it can be of any type, simple or complex object type or (escaped) html.

What I’m going to show you in this post is how to return html content in json response type. The useful thing about this technique is that you get to write your html once in a partial view, which you can then render using full page or ajax request, you can also use the same ajax request with different unrelated url that return different types. This saves you from writing too many codes for different kind of request and reduces view duplication between server and client side.

To demonstrate the trick I explained above, I will be using a mocking framework (Moq) which you can download here and reference in your project. You will also need the jquery library which you can download here.


The screenshot