I really like the
MVC Framework (not to be confused with the
MVC Pattern) from Microsoft. It allows me to take advantage of the C# programming language and
ASP.NET Web Application Framework, while giving me back some of the control over the HTML and forms that I feel I lose with the traditional ASP.NET framework. It just feels cleaner and more natural to me.
But the MVC Framework itself is not what I want to write about. What I'm excited about is how extremely easy it is to make AJAX requests on the MVC Framework with a little help from
JQuery.
Suppose I have an MVC View called "Home" with the following HTML Form:
<form method="post" action="" id="time">
<input type="text" id="txtTime" />
<input type="submit" value="Get Server Time" />
</form>
Simple, right? It consists of nothing other than an empty textbox and a submit button. The form should look something like this (with a little extra CSS sprinkled here and there:
Now, what we want to do is click the submit button (captioned "Get Server Time") and see the server time in the textbox without any postback (or page re-load, which is where the AJAX comes in).
In its latest release of the MVC Framework, Microsoft has included some AJAX-related scripts to help you accomplish this easily, and they're ok... but I would argue that JQuery makes it even easier.
Consider the following JQuery code:
$().ready(function() {
$('#time').submit(function() {
$.get('/home/gettime', null, function(data) {
$('#txtTime').val(data);
});
return false;
});
If you've never played around with
JQuery before, the above code may seem a little foreign and perhaps strange. That's ok. Allow me to explain it line-by-line:
$().ready(function() {
The line of code above essentially says "when the HTML page/document is ready (or loaded), execute the following code"
$('#time').submit(function() {
This line says "find any object in on the page with an ID of "time" (in our case, the form), and run the following code when that form is submitted.
$.get('/home/gettime', null, function(data) {
When the form is submitted, make a call to the URL "/home/gettime". Send no paramaters ("null"), and perform the following function when the data from that URL is returned.
$('#txtTime').val(data);
Set the value of the object with an ID of "txtTime" to whatever was returned by the AJAX request to "/home/gettime".
Finally,
return false;
prevents the form from being submitted normally.
The actual AJAX request was made by the
$.get()
function. In JQuery, the dollar sign "$" is just shorthand for JQuery itself. The get() function is all that is needed to perform an AJAX request. Once that request is made, you can do whatever you want with the data that is returned.
Pretty easy, huh? Now this is obviously an overly-simplified example. The cool thing about JQuery is how fast and easy it is to spice up your existing code.
The Server-side code for the above example would look something like this:
public string GetTime()
{
return DateTime.Now.ToString();
}
Nothing fancy. Just returns a string representation of the current Date. But what if we want to get a little more complex? JQuery and the MVC Framework work very well together when it comes to
JSON objects. With JSON, you can essentially work with your C# objects in Javascript. Its nothing new, but it is a powerful way to pass data back and forth between your AJAX requests.
As an example, lets say we want to build a checkbox list via AJAX based on some data we have somehow obtained (for example, from a database).
To start off, we have the following C# class (using ASP.NET 3.5 code):
public class Checkbox
{
// Properties
public string ID { get; set; }
public string Text { get; set; }
public bool Checked { get; set; }
// Constructor
public Checkbox(string ID, string Text, bool Checked)
{
this.ID = ID;
this.Text = Text;
this.Checked = Checked;
}
}
So we have a custom class with three properties: ID, Text, and Checked. Now let's build a list of Checkboxes using some data we have on hand:
List<Checkbox> Checkboxes = new List<Checkbox>();
Checkboxes.Add(new Checkbox("id1", "I like ASP.NET", false));
Checkboxes.Add(new Checkbox("id2", "ASP.NET MVC Rocks!", true));
Checkboxes.Add(new Checkbox("id3", "I like rabbits", false));
By using the JsonResult object in the MVC Framework, we can pass this strongly-typed object back to the Javascript that made the AJAX request with the following function:
public JsonResult GetCheckboxes()
{
List Checkboxes = new List();
Checkboxes.Add(new Checkbox("id1", "I like ASP.NET", false));
Checkboxes.Add(new Checkbox("id2", "ASP.NET MVC Rocks!", true));
Checkboxes.Add(new Checkbox("id3", "I like rabbits", false));
JsonResult result = new JsonResult();
result.Data = Checkboxes;
return result;
}
With the following JQuery code, we can call the function above, and iterate through the results to build the HTML we want to insert into the HTML page:
$('#json').submit(function() {
$.getJSON('/home/getcheckboxes', null, function(data) {
var html = '';
for (var i in data)
{
html += '<input type="checkbox" id="' + data[i].ID + '"';
if (data[i].Checked) html += 'checked';
html += '>';
html += '<label for="' + data[i].ID + '">' + data[i].Text + '</label><br />';
}
$('#json-span').html(html);
});
return false;
});
So assuming we have a form that contains this HTML:
<form method="post" action="" id="json">
<span id="json-span"></span>
<input type="submit" value="Get JSON Result" />
</form>
and looks like this before we click anything:
We end up with this after we click the "Get JSON Result" button:
It might not be as mindless and simple as some of the other AJAX frameworks out there, but it gives me absolute control over what happens on the page, and how it is displayed. I love it!
Feel free to
download the above code to play around with. I have also included some simple animation examples using JQuery to showcase just how easy it is to get started.
More Information:
JQuery Library
50+ Amazing JQuery Examples