ASP.NET MVC 2 and MongoDb Part 4 – First steps with jQuery, AJAX and JSON

In the past articles we created a simple application to submit bugs to a project. If you run the BugBase app, it looks like this:



It's ugly!
Let's add some style quickly. And since I am not a webdesigner, I Google for 'minimalist templates' and grab a free one, like this one, courtesy to Cardeo.

Masterpages are around for eons, so I won't go into the technical details of this phenonemon much. After creating a masterpage from Cardeo's design, BugBase looks like this:

And the bug submitform:

It's slightly better, no?

JavaScript, Ajax and JSON

Ajax is a technique that provide a snappier user experience through the use lightweight calls to the web server, in stead of full roundtrips to the server every time you submit a form. These asynchronous calls are initiated on the client using JavaScript and involve formatting data, sending it to a web server, and parsing and working with the returned data. While most browsers can construct, send, and parse XML, JavaScript Object Notation (or JSON) provides a standardized data exchange format that is better-suited for Ajax-style web applications. (Okay, I didn't write the last paragraph myself, Microsoft did. But I never found a more clever desription of the JQuery. AJAX and JSON triade.)

So, let's Ajaxify the Bug submit form. Let's make use of the jQuery Form Plugin, which actually does everything for you. Just copy jquery.form.js to the Scripts folder and make references in the head sections of Create.aspx (or in the BugBase.Master).

Next, I'm going to go ahead and add my own .js file (Add, New Item) to the scripts folder for my jQuery code. Also add a reference to this script:

<head>
<title>BugBase the Bug submitting app</title>
 <link href="../../Content/style.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
 <script type="text/javascript" src="../../Scripts/jquery.form.js"></script>
  <script type="text/javascript" src="../../Scripts/BugBase.js"></script>
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>

Next thing we need to do, is add an ID to the /Bug/Create form. As you can see, the HTML is rendered with the help of HTML Helpers (hm, so that's where those helpers get their names from) but I am not sure if HTML is better with or without these helpers. So, I just click on View Source in my browser and copy the generated HTML to Create.aspx. Next, I can add an ID to the form, which is important because this is how the jquery.form.js references the submit form.

<form action="/Bug/Create" method="post" id="BugSubmitform"> 
            <div class="editor-label"> 
                <label for="Name">Name</label> 
            </div> 
            <div class="editor-field"> 
                <input id="Name" name="Name" type="text" value="" /> 
            </div> 
            <div class="editor-label"> 
                <label for="Description">Description</label> 
            </div> 
            <div class="editor-field"> 
                <textarea cols="20" id="Description" name="Description" rows="2"> 
            </textarea> 
            </div> 
            <p> 
                <input type="submit" value="Create" /> 
            </p> 
    </form>
<h6><h6>

Next step is edit the (still empty) BugBase.js and add the following code:

$(document).ready(function () {
    $('#BugSubmitform').ajaxForm({
        dataType: 'json',
        success: function (response) {
              $('h6').text("Bugname: " + response.Name + ".  
                     And the description is: " + response.Description);
              alert(response.Description);
        }
    });
});

Hmm, this is pretty self-explanatory I think? The first line you should know by heart if you plan to write more jQuery.
The next thing you see how we reference the id of the form, i.c. #BugSubmitform. So the form plugin knows at which point it should wake up. Then we are specifying the dataType, which is json. On success, we're going to display an alert, with the Description of our bug. Also, we will display the bug name and bug description between H6 tags, which I added on the Create.aspx page.

You see, 'response' in line 5 is actually the submitted bug serialized in json format. So, we can use all the properties of the Bug class here!

We're not completely finished though. We'll have to make sure the Create function of our controller actually returns JSON. Which is in fact very easy:

[RequiresAuthentication]
[HttpPost]
public ActionResult Create(Bug bug)
        {
            BugSession.Save(bug);

            if (Request.IsAjaxRequest())
            {
                return Json(bug);
            }

            return new RedirectResult("Create");
        }
    }

That's it. Let's try it.

To see that we really really Ajaxified things, we should fire Firebug form Firefox. If you check out the console, you'll notice the XMLHttpRequest, which proves that this was an AJAX request and the returnformat is JSON:

So now we know how we can speed up our app by using AJAX and jQuery and how we can provide the user feedback with the JSON result. As soon as I completed the BugBase app, I will post it here for you to download.

3 Replies to “ASP.NET MVC 2 and MongoDb Part 4 – First steps with jQuery, AJAX and JSON”

Leave a Reply to matt Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.