MVC Web Application and JSON

Tags: .NET, AJAX, HTML, JavaScript, jQuery, JSON, Mobile, MVC, Source Code

I like the MVC (Model View Controller) framework which is available as a public CTP, now. You can download the latest bits with the ASP.NET 3.5 Extensions CTP Preview. You will find further links at Scott Guthrie's posts tagged with MVC.

While playing around I tried to create a simple Web page that will render an address from a given ID (well, I don't use any real data, so the ID will simply added to the end of the comany name etc.).

image

If you have a look at the address line you will see the ID for the record at the end. This ID is used for the MVC controller to "read" the record.

image

Now I'd like to extend the example with a some JavaScript to read the next data when clicking on the Next button. Using jQuery I create a request to the same URL and adding an http header to identicate that I'd like to get the response as JSON data.

image

In my Controller class I check if the http header is sent or not. If I find the http header I serialize the data to JSON with the .NET built-in JavaScriptSerializer.

image

The Web browser get the serialized data and updates the display using the unique HtmlControl IDs.

Well, this was a very simple example showing how we can use the same Controller for different views. As you maybe have noticed I check f the Web browser is a mobile device in my controller, too, to render a different html for mobile devices.

3 Comments

  • Nikolas Coukouma said

    It's worth noting that care should be taken with sending JSON. Unless some safeguard is in place, another (possibly malicious) site can load the data using a script tag (by overriding the Object constructor in JS). There's also the usual CSRF/XSRF problem to consider. I'm not criticizing this post, of course; it's supposed to be simple). I'm just leaving a gentle reminder. Also, in this case, the use of an extra HTTP header (x-json) provides protection against the script tag attack. ... Another note: it would be more standards-friendly to send the POST request with the header "Content-Type: application/json"

  • interactive said

    @Nikolas: well, I my eyes there are enough ways to ensure that this is not possible. And the x-json header is only a dummy header value as the Content-Type in some browsers is not working that I'm working with. But you are correct if we use JSON we should use the application/json content type. Michael

  • alerch said

    Good stuff! Here's another take on exposing your MVC data as JSON (or XML). http://www.aaronlerch.com/blog/2008/01/01/unifying-web-sites-and-web-services-with-the-aspnet-mvc-framework/

Comments have been disabled for this content.