MVC: A Cascading Dropdown using AJAX and jQuery - VB.Net Version
Language(s):C#, jQuery
Category(s):AJAX, ASP.Net, MVC
This article will show you how to write a Model View Controller (MVC) project that will make use of a cascading dropdown using JQuery and AJax.

See also: C# Version

This article assumes you are using Visual Studio 2008 and have downloaded and installed MVC, which is available from Microsoft for free at: http://www.asp.net/mvc/, where you will also find a number of useful tutorials that will get you started writing MVC applications.

This app will be a simple two dropdown app. The first dropdown allows the user to select a color. The second dropdown lists foods that have the color selected – see Figure 1.

Figure 1 – Screenshot of the sample application.

 

To get started, you will want to create an MVC project. Your default project should already have the standard jQuery library located in the /Scripts folder. You should also find a document under /Views/Home/ named Index.aspx. Double-click the Solution Explorer to bring up the Edit Window for Index.aspx. For this application, we only need the standard jQuery library – which at the time of this writing is jquery-1.3.2.js. If you have a more recent version, you should find that it will work as well.

Before we can write the jQuery code, we need to define the jQuery library. Generally speaking, you will want to do this in the Master Page. For the default MVC project, you will find the Master Page under the /Shared folder with a name of Site.Master. Open this file in the editor and define the jQuery library inside the head tag. When you are done, the head tag of Site.Master should look like the following:

<head runat="server">

    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" />

    </title>

    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript"

        language="javascript" src="../../Scripts/jquery-1.3.2.js">

    </script>

</head>

 

Be sure to use both a beginning and ending script tag as opposed to a <script /> tag or you will probably find that you have issues!

The default MVC project will also have the default view located at /Views/Home/Index.aspx. Double-click this file in the Solution Explorer to bring up the Edit Window. We will replace the “MainContent” tag with the following:

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

  <table title="Food Selector">

    <tr>

     <td>Select a Color:</td>

     <td>

        <select id="Colors">

          <option id="0">Select...</option>

          <option id="1">Black</option>

          <option id="2">Blue</option>

          <option id="3">Brown</option>

          <option id="4">Green</option>

          <option id="5">Red</option>

          <option id="6">White</option>

          <option id="7">Yellow</option>

        </select>

     </td>

    </tr>

    <tr>

     <td>Select a Food:</td>

      <td>

        <select id="Foods">

          <option>Select...</option>

        </select>

      </td> 

    </tr>

  </table> 

</asp:Content>

 

If you run the project at this point, you should see something similar to Figure 1, but nothing will happen yet when you select a color.  

Next, let’s write some jQuery. The jQuery code will run when the Colors dropdown has been selected. It will pass the selected color via an AJAX request to our MVC application, which will return a list of foods matching that color. Our client side code will then load the Foods dropdown with the list returned from the server.

The jQuery will be written inside another script tag, but this one will be placed in the MainContent content tag just above the table tag.

Since we don’t want to run this code until the document has loaded, we will wrap the code inside the jQuery $(document).ready event. I usually like to begin with a simple alert statement to make sure everything is defined and hooked up correctly.

If you have not worked with jQuery before, you may find the syntax a bit confusing at first complete with an array of endless parenthesis and brackets. You may find it useful to always define your beginning and ending delimiters together. So, for example, I would first define the $(document) block, and then fill in with the rest of my code. So I would first write this: 

    <script type="text/javascript" language="javascript">

        $(document).ready(

  );

    </script>

…and then define the function body:

    <script type="text/javascript" language="javascript">

        $(document).ready(function() {

        });

    </script>

 

 …followed by the alert statement:

    <script type="text/javascript" language="javascript">

        $(document).ready(function() {

            alert("It's not broken!");

        });

    </script>

 

Now if you run the project, you should see the page load as before, followed by the message box. I like to code incrementally in this way. If it works so far, you are good. If not, you might as well deal with it while it’s simple before moving on.

So, assuming the basic shell of the application is working ok so far, we can start making it do something. Let’s modify the alert statement so it fires when we select something from the Colors dropdown and announces which item was selected.

jQuery is all about selectors. To hook into the change event of any dropdown we can use the $(“select”) selector. This selects *all* dropdowns on the page. Since we only want this code to fire when the Colors dropdown is selected, we can further qualify this with the id of the tag – like this: $(“select#Colors”), which tells jQuery ‘Select the dropdown whose id = “Colors”.’ We want to hook into the change event, so we can define an event handler to run when the Colors dropdown is selected like this:

   $("select#Colors").change(function() {

        //code to run during the change event goes here

   });

 

We can now modify our alert statement to tell us the id of the selected item using this syntax:

   $("select#Colors").change(function() {

       alert($("select#Colors option:selected").attr("id"));

   });

 

The entire script tag should now look something like the following:

    <script type="text/javascript" language="javascript">

        $(document).ready(function() {

            $("select#Colors").change(function() {

                alert($("select#Colors option:selected").attr("id"));

            });

        });

    </script>

 

When you run the project, selecting a color should pop up a message box with the selected id, so selecting the color Red should pop up the number 5. We will pass this number via AJAX to the server side code and load the Foods dropdown with the result.

Next, let’s look at how to add the AJAX call. We will use the getJSON method to pass the selected id to the server and return the list of foods related to the selected color. The method will be defined in the HomeController, have the name of GetFoots and accept an integer. In MVC syntax, this translates to an URL that looks like ‘Home/GetFoods/3’ where ‘3’ is the id of the selected color. The code to grab the selected id and make the AJAX call looks like this:

    var id = $("select#Colors option:selected").attr("id");

    $.getJSON("Home/GetFoods/" + id, function(foods) {

        //Code to load the dropdown goes here

    });

 

Ok – almost done with the client side code. The foods parameter will have a list of foods. Now we just need to iterate this list, build the HTML for the dropdown and update. Iterating the foods list can be done using the $.each method. We will iterate for each food, build an option tag and then at loop end use the .html() method to set the Foods dropdown. The complete listing for our client side script now looks like the following:

    <script type="text/javascript" language="javascript">

        $(document).ready(function() {

            $("select#Colors").change(function() {

                var id = $("select#Colors option:selected").attr("id");

                $.getJSON("Home/GetFoods/" + id, function(foods) {

                    var html = "";

                    $.each(foods, function(index, value) {

                        html += ("<option>" + value + "</option>");

                    });

                    $("select#Foods").html(html);

                });

            });

        });

    </script>

 

That’s it for the client side code. Now let’s look at what’s happening on the server side. For simplicity sake, we will just use a case statement to return a string array – but in the real world, we would probably involve a database to lookup the parent id and return the detail list.

To write the server side code, we will edit HomeController.cs (or HomeController.vb for a VB.Net application) located under the /Controllers folder. This routine will accept an integer representing the id, and return a string array as a JsonResult. Here is the complete listing for this method:

    Function GetFoods(ByVal id As Integer) As JsonResult

 

        Const ID_BLACK = 1

        Const ID_BLUE = 2

        Const ID_BROWN = 3

        Const ID_GREEN = 4

        Const ID_RED = 5

        Const ID_WHITE = 6

        Const ID_YELLOW = 7

 

        Dim black As String() = {"Beens", "Black rice", "Coffee", "Raisins"}

        Dim blue As String() = {"Blueberries", "Blue Corn", "Blue Cabbage"}

        Dim brown As String() = {"Brown Rice", "Brown Sugar", "Brownies", _

                                 "Wheat Bread"}

        Dim green As String() = {"Broccoli", "Lettuce", "Kale", "Spinich"}

        Dim red As String() = {"Kidney Beans", "Radishes", "Tomatoes"}

        Dim white As String() = {"Hominy", "White Bread", "White Rice"}

        Dim yellow As String() = {"Butter", "Corn", "Squash"}

 

        Select Case (id)

            Case ID_BLACK

                Return (Json(black))

            Case ID_BLUE

                Return (Json(blue))

            Case ID_BROWN

                Return (Json(brown))

            Case ID_GREEN

                Return (Json(green))

            Case ID_RED

                Return (Json(red))

            Case ID_WHITE

                Return (Json(white))

            Case ID_YELLOW

                Return (Json(yellow))

            Case Else

                Return (Json("Select..."))

        End Select

 

    End Function

That’s all there is to it. You will find that this works much better than posting back the entire page to respond to a dropdown. The complete code for this project can be downloaded from the link above. Have fun!!

 

From: jsmith123 - 2014-05-04
test

This article has been viewed 22274 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.