MVC Web Application and JSON

Michael Schwarz on Wednesday, December 19, 2007

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 [1]. You will find further links at Scott Guthrie's posts tagged with MVC [2].

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.