Today I populated an html div element asynchronously using jQuery and JSON in my ASP.NET MVC2 project. Now, when you were 10 years old, did you think you'd one day find a sentence like that above interesting? I bet not. But here's why it is (lol) :

In MVC you're allowed to mix javascript code (client side) with C# code (server side), but you have to understand where each part of it is being run. Here's the code (the important parts of it anyway):

Client side (mostly):

<script type="text/javascript">
$(document).ready(function() {
$.getJSON('<%=Url.Action("GetJsonDriveList", "DiskSpace") %>', function(jsonData) {

for (i = 0; i < jsonData.length; i++) { $.get('<%=Url.Action("LoadDiskSpace", "DiskSpace") %>?serviceAddress=' + jsonData[i].serviceName, function(data) {
$("#mainDiv").append(data);
});
}
});
});
</script>

Server side :
public class DiskSpaceController : Controller {
public JsonResult GetJsonDriveList()
{
return Json(GetDriveList(), JsonRequestBehavior.AllowGet);
}

public List GetDriveList() {
// yada yada
}

public PartialViewResult LoadDiskSpace(string serviceAddress)
{
var drives = GetDiskSpace(serviceAddress);
var aDriveModel = new DiskDriveModel(drives[0]);

return PartialView("_Drive", aDriveModel);
}
//........
}

jQuery : javascript library that makes it easy to do asynchronous server requests and select elements on a webpage.
JSON: JavaScript Object Notation. Makes it easy to convert C# objects to Javascript objects and vice versa.(e.g. list converts to javascript Array()....etc.)

OKAY!

So first off the client side stuff. That's a script tag you can put on a view (MVC term) and it'll run when the page loads. (OH make sure you've referenced jQuery.js, microsoftAjax.js and microsoftMvcAjax.js first, btw). Everything inside the <% %> tags runs SERVER side, and the other stuff runs client side. And the Url.Action call might seem wierd, but all it does is construct a url that looks like "DiskSpace/LoadDiskSpace" and the "?serviceAddress=..." is the querystring that will be sent with the jQuery GET request.

So the $(document).ready part only runs when the DOM (document object model) is ready. This is the first thing you do ANYtime you run jQuery, as far as I know. Then $.getJSON sends a request to the server and expects a result in the form of a JSON object. When the result is returned, the callback is run, and in the callback we send another request, this time for a PartialView to be inserted into our div element with id "mainDiv".

Now the server side stuff. There's some stuff in MVC that maps the request (e.g. "DiskSpace/GetJsonDriveList") to an action method in a controller. "DiskSpace" is the controller (or the class, to put it simply) and "GetJsonDriveList" is the name of the action method to run and get the result from. So the method is run, and returned as a JSON object using Json(ObjectToReturn, JsonRequestBehavior.AllowGet). The "AllowGet" cannot be left out or else you won't get anything returned and will stare at the screen for hours in a state of frustration!! And then, when the client side receives it, it can be interpreted easily. The next action method that's called has the same idea, but without the json : it creates a View with PartialView("ViewName", modelObject) and then returns it to the client side.

MVC makes web development easy...but jQuery and JSON make it easier! If you wanna make a webpage ever (and you don't know ruby on rails), d/l the plug-in from pluralsight and watch the free screencasts, they're SUPER easy to follow and get you started quickly.

Hope this was...entertaining? ... lol

Comments

  1. Hello, I have just started reading and trying the assignments in the book Absolute Java by Savitch. I came upon your site while looking to double check my programs, however, I noticed your solution links are no longer working. Would you be so kind to reupload them? Thank you

    ReplyDelete
  2. I believe they're working now! Thx for subscribing.

    ReplyDelete

Post a Comment

Popular Posts