CascadingDropDown jQuery Plugin for ASP.NET MVC - Raj Kaimal

CascadingDropDown jQuery Plugin for ASP.NET MVC

Cascading Drop Down is a jQuery plug-in that can be used by a select list to get automatic population using AJAX. The plug-in and a sample ASP.NET MVC project are attached at the bottom of this post.

image 
Usage
The code below shows two select lists :

<select id="customerID" name="customerID">
  <option value="ALFKI">Maria Anders</option>
  <option value="ANATR">Ana Trujillo</option>
  <option value="ANTON">Antonio Moreno</option>
</select>
 
<select id="orderID" name="orderID">
</select>

The following code causes the second list to auto populate when a customer is selected in the first list.

$("#orderID").CascadingDropDown("#customerID", '/Sales/AsyncOrders');

Internally, an AJAX post is made to ‘/Sales/AsyncOrders’ with the post body containing  customerID=[selectedCustomerID]. This executes the action AsyncOrders on the SalesController with signature AsyncOrders(string customerID).  The AsyncOrders method returns JSON which is then used to populate the select list. The JSON format expected is shown below :

[{
    "Text": "John",
    "Value": "10326"
},
{
    "Text": "Jane",
    "Value": "10801"
}]


Details

$(targetID).CascadingDropDown(sourceID, actionPath, settings)

  • targetID
    The ID of the select list that will auto populate. 
  • sourceID
    The ID of the select list, which, on change, causes the targetID to auto populate.
  • actionPath
    The url to post to

Options

  • promptText
    Text for the first item in the select list
    Default : -- Select --
  • loadingText
    Optional text to display in the select list while it is being loaded.
    Default : Loading..
  • errorText
    Optional text to display if an error occurs while populating the list
    Default: Error loading data.
  • postData
    Data you want posted to the url in place of the default
    Example :

    postData: function () {
        return { prefix: $('#txtPrefix').val(), customerID: $('#customerID').val() };
    }
    will cause prefix=foo&customerID=bar to be sent as the POST body.
    Default: A text string obtained by calling serialize on the sourceID

  • onLoading (event)
    Raised before the list is populated.
  • onLoaded (event)
    Raised after the list is populated, The code below shows how to “animate” the  select list after load.

Example using custom options:

$("#orderID").CascadingDropDown("#customerID", '/Sales/AsyncOrders',
{
    promptText: '-- Pick an Order--',
    onLoading: function () {
        $(this).css("background-color", "#ff3");
    },
    onLoaded: function () {
        $(this).animate({ backgroundColor: '#ffffff' }, 300);
    }
});


To return JSON from our action method, we use the Json ActionResult passing in an IEnumerable<SelectListItem>.

public ActionResult AsyncOrders(string customerID)
{
    var orders = repository.GetOrders(customerID).ToList().Select(a => new SelectListItem()
    {
        Text = a.OrderDate.HasValue ? a.OrderDate.Value.ToString("MM/dd/yyyy") : "[ No Date ]",
        Value = a.OrderID.ToString(),
    });
    return Json(orders);
}


jQuery Plug-in
Now hosted on GitHub

Sample Project using VS 2010 RTM (updated 5/21/2010)


Comments and suggestions are welcome.

Other Posts

Published Thursday, May 20, 2010 1:55 AM by rajbk
Filed under: , , , ,

Comments

# Twitter Trackbacks for CascadingDropDown jQuery Plugin for ASP.NET MVC - Raj Kaimal [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 CascadingDropDown jQuery Plugin for ASP.NET MVC - Raj Kaimal         [asp.net]        on Topsy.com

# May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight | OOP - Object Oriented Programing

Pingback from  May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight | OOP - Object Oriented Programing

# ScottGu&amp;#8217;s May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight &#171; Code Name &quot;NitRiX Reloaded&quot;

Pingback from  ScottGu&amp;#8217;s May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight &#171; Code Name &quot;NitRiX Reloaded&quot;

# CascadingDropDown jQuery Plugin for ASP.NET MVC - Raj Kaimal

9efish.感谢你的文章 - Trackback from 9eFish

Tuesday, May 25, 2010 2:15 AM by 9eFish

# re: CascadingDropDown jQuery Plugin for ASP.NET MVC

Hi, this is an excellent script, exactly what I have been looking for. I have one small question, is it possible to reload the lists and select default values, basically be able to retain the selected values after a postback?

Wednesday, May 26, 2010 12:30 PM by scout7

# May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight | Tweetland&#039;s Adventures

Pingback from  May 20th Links: ASP.NET MVC, ASP.NET, .NET 4, VS 2010, Silverlight | Tweetland&#039;s Adventures

# re: CascadingDropDown jQuery Plugin for ASP.NET MVC

Very cool. Great work, I was looking something like this. You save me some time :)

Friday, May 28, 2010 12:31 PM by cibrax

# re: CascadingDropDown jQuery Plugin for ASP.NET MVC

Nice work!

Wednesday, June 02, 2010 3:46 AM by Michiel

# re: CascadingDropDown jQuery Plugin for ASP.NET MVC

nice one..very useful

Friday, June 04, 2010 12:49 AM by sandy060583

# Dew Drop &#8211; June 4, 2010 | Alvin Ashcraft&#039;s Morning Dew

Pingback from  Dew Drop &#8211; June 4, 2010 | Alvin Ashcraft&#039;s Morning Dew

# re: CascadingDropDown jQuery Plugin for ASP.NET MVC

   $.fn.CascadingDropDown.defaults = {

       promptText: '-- 请选择 --',

       loadingText: '加载中...',

       errorText: '加载失败',

       postData: null,

       onLoading: null,

       onLoaded: null,

       dataType: 'json'

   }

and

                           success: function (data) {

                               methods.reset();

                               if (config.dataType == 'html') {

                                   $this.html(data);

                               }

                               else {

                                   var dataHtml = '';

                                   for (var item in data) {

                                       dataHtml += $(optionTag).attr("value", this.Value).text(this.Text)

                                   }

                                   this.html(dataHtml); ;

                               }

                               methods.loaded();

                               $.isFunction(config.onLoaded) && config.onLoaded.call($this);

                           },

Friday, June 18, 2010 2:53 AM by ohaiyo

# 使用json 和jQuery制作级联dropdownlist

作者: geff zhang 发表于 2010-07-04 16:48 原文链接 阅读: 13 评论: 0 联动式的下拉选择是一个很普遍的需求,在ASP.NET MVC中可以使用Json和jQuery来实现

Sunday, July 04, 2010 6:05 AM by ASP.NET Chinese Blogs

# Links Interesantes de .NET en general

Links Interesantes de .NET en general

Monday, September 27, 2010 5:20 PM by Phydelta

# problems with casceding dropdowns | Info

Pingback from  problems with casceding dropdowns | Info

Tuesday, September 28, 2010 2:13 AM by problems with casceding dropdowns | Info

# CascadingDropDown jQuery Plugin for ASP.NET MVC &laquo; Bhavin Patel

Pingback from  CascadingDropDown jQuery Plugin for ASP.NET MVC &laquo; Bhavin Patel

Wednesday, November 17, 2010 3:09 PM by CascadingDropDown jQuery Plugin for ASP.NET MVC « Bhavin Patel

# Adding additional input fields dynamically (similar to SO careers) - Question Lounge

Pingback from  Adding additional input fields dynamically (similar to SO careers) - Question Lounge

# Have you got a CascadingDropDown working with ASP.NET MVC? | C Language Articles | C + Language Tutorial

Pingback from  Have you got a CascadingDropDown working with ASP.NET MVC? | C Language Articles | C + Language Tutorial

# Why Did I Wait This Long To MVC / Razor? &#8211; Henry Chong

Pingback from  Why Did I Wait This Long To MVC / Razor? &#8211; Henry Chong

Wednesday, July 04, 2012 2:59 AM by Why Did I Wait This Long To MVC / Razor? – Henry Chong