ASP.NET MVC – jQuery – Json.. Cascading Dropdown

I’m less interested in the ‘cascading dropdown’ part of this post , as I am in demonstrating how json and jquery can be your friends in the asp.net mvc world.

Let’s start by a description of the ‘problem’:  On populating a page, we need to query for a set of companies and display those to the user.  Upon selection of a company, we need to populate another dropdown of the banks associated to that company.  You can fill in the blanks for ‘companies’with ‘banks’ – basically a one to many.  In my situation, I use lazy loading and do not need to pull all the banks in when the page loads.

First let’s look at the ‘onLoad’ of the page via jQuery:
$(function () {
  $("#companies").change(function () {
    LoadBanks($("#companies").val());
    });
  });

I’ve simplified this from the code to show the essentials.  I’m handling the onChange of the companies drop down list, something like this:
Select Company: <%= Html.DropDownList("companies", new SelectList(Model, "Companyid", "Name"), string.Empty)%>
The Model is my list of ‘Company’ objects.  The value is the id and the text is the name.
From the above javascript, you’ll see that when the dropdown item is selected I will be passing the selected value – which is the id – to the LoadBanks function:

function LoadBanks(companyId) {
 $.ajax({
  type: "POST",
  url: BuildUrl("Company/LoadBanks"),
  data: ({ id: companyId }),
  dataType: "json",
  beforeSend: function () {
$.blockUI({ message: "Retrieving Banks..." });   //this is great plugin - 'blockUI'
},
success: function (positivePayBanks) {
  $("#positivePayBanks").find('option').remove();
  $banks = $("#positivePayBanks");
  $.each(positivePayBanks, function (i, bank) {
  if (i == 0) { $("#BankID").val(bank.BankID); }
   $banks.append('<option value="' + bank.BankID + '">' + bank.BankName + '</option>');
  });
$.unblockUI();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
  $.unblockUI();
  var errMsg = "<P>Error Loading: " + XMLHttpRequest.responseText + "<br/>";
  $("#status").html(errMsg).show("slow");
}
});
}

So, what is going on in this call?

type: "POST"
url: BuildUrl("Company/LoadBanks"),   <-- the BuildUrl is just a helper call - basically this is the REST call to the controller/action
data: ({ id: companyId }),   <-- this is the params being sent to the Action.  I'm passing the selected company id
dataType: "json",   <--  I'm saying that the returning data will be json.

Let’s step out of the javascript/html to just show how easy it is to serialize the list of banks to json in mvc:
This isn’t too exciting but here is the controller action for ‘LoadBanks’:

[HttpPost]    <-- I'm requiring this to be a post here
public ActionResult LoadBanks(string id) <--- this id will pick up the id passed in the ajax call above
{
  var positivePayBanks = _companyService.GetBanksByCompanyId(new Guid(id));
  return Json(positivePayBanks);
}

Pretty boring isn’t it?  The simplicity here is appreciate though as mvc includes a JsonResult that will take the list of banks and generate the json!
Here is the select html:

<select id="positivePayBanks" class="required"></select>

The meat here of the post is how we can take that resulting json data and ‘bind’ it to the bank dropdown:

success: function (positivePayBanks) {   <--- 'positivePayBanks' is the returning json data
  $("#positivePayBanks").find('option').remove();     <--- this clears it each time, as it will continue to just append if I don't first remove it!
  $banks = $("#positivePayBanks");
  $.each(positivePayBanks, function (i, bank) {    <--- the beauty of jQuery here is a nice foreach statement
   if (i == 0) { $("#BankID").val(bank.BankID); }    <-- I'm actually forced to set the id of the selected bank or the form post doesn't catch it.
   $banks.append('<option value="' + bank.BankID + '">' + bank.BankName + '</option>');   <-- append the results to the select
  });
$.unblockUI(); //unblock the UI
}

I left the blockUI in this sample because I want to remind those using ajax, that there is no control over the latency on the network – so rather than leave the user wondering what just happened, this gives a visible indicator.
For those new to Json, the part I like the best here is that jQuery will deserialize the json data into the ajax result:
(success: function (positivePayBanks))
Since this is a list of banks, we can use jQuery to loop through each one and it is represented as a bank object, which allows for the ‘bank.BankID’ and ‘bank.BankName’
Just as a finishing note, it is possible to just return a partialview with a Html.DropdownList , etc..  – however, by using Json , it greatly decreases the transmission over the wire.  Json is a perfect medium for keeping the data minimal, and as you can see it goes hand in hand with frameworks like jQuery.
One piece of this I do not like, is how I needed to then set the selected bankId to a hidden field.  I was able to get the value passed into the form collection on form post naturally.  If anyone has a trick for that- let me know  🙂
PS. I’m still looking for a good WordPress application to run on MacBook

Review of Building a Java Web Application with Netbeans Tutorial

I deployed for the first time a Grails app into a production Tomcat server last week.  Great experience, very straightforward – the technology has been wonderful.  I have switched back and forth between IntelliJ (my favorite for Grails, but probably won’t spend the ~$250 for it), Eclipse (through Springsource Tool Suite), and Netbeans.   I’m not really looking for the IDE to do a great deal outside of perhaps some debugging tools, intellisense, and ‘goto declaration’ type functionality I’ve been accustom to with Resharper.  Which is by the way why I think I liked IntelliJ was mostly because I’ve been a Resharper user for quite some time and I found it closer to my normal IDE experience.

But I digress.  The main reason I bring it up is because I’ve diverged into several different paths at the same time – exploring Ruby on Rails, Grails, PHP, and then Java Web applications (each has been a ‘taste of the weekend’ experience where I dedicated any development time over the weekend to a new technology).  I will say, Netbeans has build in support for all those technologies and I found it easy to use.  (ie. In the Grails project, we use Subversion, and that was very straightward to setup in Netbeans).  The guys I work with are Eclipse fans, and I understand when you have used an IDE for many years, you tend to find it to be the ‘best’.  So certainly I’m not going to start an IDE war conversation.  To each their own.   Actually, I bring up Netbeans because I’ve found their tutorials to be quite good.  For reference, I’m running this on MacBook Pro version of Netbeans 6.8.

The tutorial I’m working through is called “The Netbeans e-commerce tutorial” found here: http://netbeans.org/kb/docs/javaee/ecommerce/intro.html What I have really enjoyed with this tutorial is it takes a very holistic approach to building a Java web application.  And the tutorial isn’t really Netbeans specific, although the screenshots show ‘netbeans ide’ (in other words, you could do this in Eclipse without too much of a difference).  There aren’t too many shortcuts taken in the tutorial, including just building the database using MySQL Workbench – which I must say, the tutorial goes quite in depth in showing how to use the Workbench IDE to create a model first approach that forward engineers the creation of the tables in MySQL.  Very nicely done.

One other item to note is the attention to detail to not just ‘java’ elements, but the setup of a very well designed ‘css’ oriented html web site.  Obviously they want to show off their IDE capability with html and css, and quite honesty I was extremely impressed with the IDE capabilities especially with the CSS intellisense – which was more than just ‘intellisense’ it has great help context build in, as well as a nicely done preview pane to show you what the css class will look like ahead of time!

I’ve worked my way through the first half  of the tutorial – and will provide more feedback as I get past the modeling and html aspects.  I wanted to share that so far the experience has been very positive – and I hope as I continue through the meatier java parts of the tutorial that I can have more good things to say  🙂

Until next time, if you get a chance, check out the link provided to the tutorial and give it a whirl and let me know what you thought of the experience.