<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MIKE &#187; LINQ</title>
	<atom:link href="http://helios.ca/category/development/aspnet/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://helios.ca</link>
	<description>Just another developer blog</description>
	<lastBuildDate>Thu, 10 Jun 2010 15:02:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>ASP.NET MVC Cascading DropDownList with jQuery</title>
		<link>http://helios.ca/2009/05/30/aspnet-mvc-cascading-dropdownlist-with-jquery/</link>
		<comments>http://helios.ca/2009/05/30/aspnet-mvc-cascading-dropdownlist-with-jquery/#comments</comments>
		<pubDate>Sat, 30 May 2009 22:50:00 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#.NET]]></category>
		<category><![CDATA[Developement]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://helios.ca/?p=64</guid>
		<description><![CDATA[Here a simple example of cascading drop down list in ASP.NET MVC with jQuery. First you need models. I chosed to do this example using a Country and State dropdown, so I&#8217;m going to build to Models (Country and State) with a little bit of fake data. Lets start with the Country Model and Fake [...]]]></description>
			<content:encoded><![CDATA[<p>Here a simple example of cascading drop down list in ASP.NET MVC with jQuery.</p>
<p>First you need models. I chosed to do this example using a Country and State dropdown, so I&#8217;m going to build to Models (Country and State) with a little bit of fake data.</p>
<p>Lets start with the Country Model and Fake Data</p>
<pre name="code" class="csharp">using System.Collections.Generic;
using System.Linq;

namespace CascadingDDLjQueryDemo.Models
{
    public class Country
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }

        public static IQueryable<Country> GetCountries()
        {
            return new List<Country>
            {
                new Country {
                    CountryCode = "CA",
                    CountryName = "Canada"
                },
                new Country{
                    CountryCode = "US",
                    CountryName = "United-States"
                }
            }.AsQueryable();
        }
    }
}</pre>
<p>And now the State Model and Fake Data</p>
<pre name="code" class="csharp">using System.Collections.Generic;
using System.Linq;

namespace CascadingDDLjQueryDemo.Models
{
    public class State
    {
        public string CountryCode { get; set; }
        public int StateID { get; set; }
        public string StateName { get; set; }

        public static IQueryable<State> GetStates()
        {
            return new List<State>
            {
                new State
                    {
                        CountryCode = "CA",
                        StateID=1,
                        StateName = "Ontario"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=2,
                        StateName = "Quebec"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=3,
                        StateName = "Nova Scotia"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=4,
                        StateName = "New Brunswick"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=5,
                        StateName = "Manitoba"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=6,
                        StateName = "British Columbia"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=7,
                        StateName = "Prince Edward Island"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=8,
                        StateName = "Saskatchewan"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=9,
                        StateName = "Alberta"
                    },
                new State
                    {
                        CountryCode = "CA",
                        StateID=10,
                        StateName = "Newfoundland and Labrador"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=11,
                        StateName = "New-York"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=12,
                        StateName = "California"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=13,
                        StateName = "Washington"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=14,
                        StateName = "Vermont"
                    }
            }.AsQueryable();
        }
    }
}</pre>
<p>We can now add List methods in the controller. I chosed to return both Json and View so I could decide to make a page CountryList and use the same method.</p>
<pre name="code" class="csharp">using System.Linq;
using System.Web.Mvc;
using CascadingDDLjQueryDemo.Models;

namespace CascadingDDLjQueryDemo.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CountryList()
        {
            IQueryable countries =
                Country.GetCountries();

            if(HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(
                                countries,
                                "CountryCode",
                                "CountryName")
                            );

            return View(countries);
        }

        public ActionResult StateList(string CountryCode)
        {
            IQueryable states = State.GetStates()
                .Where(x =&gt; x.CountryCode == CountryCode);

            if (HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(
                                states,
                                "StateID",
                                "StateName")
                            );

            return View(states);
        }
    }
}</pre>
<p>And now we require Routes to access this data</p>
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CascadingDDLjQueryDemo
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "StatesList",
                "Home/States/List/{CountryCode}",
                new { controller = "Home", action = "StateList", CountryCode = "" }
            );

            routes.MapRoute(
                "CountriesList",
                "Home/Countries/List",
                new { controller = "Home", action = "CountryList" }
            );

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = "" }
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}</pre>
<p>The Javavascript</p>
<pre name="code" class="javascript">$(function() {
        $.getJSON("/Home/Countries/List", function(data) {
            var items = "
<option>---------------------</option>

";
            $.each(data, function(i, country) {
                items += "
<option value='"+country.Value+"'>" + country.Text + "</option>

";
            });
            $("#Countries").html(items);
        });

        $("#Countries").change(function() {
            $.getJSON("/Home/States/List/" + $("#Countries &gt; option:selected").attr("value"), function(data) {
                var items = "
<option>---------------------</option>

";
                $.each(data, function(i, state) {
                    items += "
<option value='"+state.Value+"'>" + state.Text + "</option>

";
                });
                $("#States").html(items);
            });
        });
    });</pre>
<p>And finally, the Index View.</p>
<pre name="code" class="xhtml">
<h2>ASP.NET MVC Cascading DropDownList using jQuery</h2>

<label for="Countries">Countries</label>
<select id="Countries" name="Countries"></select>

        <label for="States">States</label>
<select id="States" name="States"></select>
</pre>
<p>You can find the <a href="http://www.helios.ca/wp-content/uploads/2009/05/CascadingDropDownListJquery.zip">source code here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://helios.ca/2009/05/30/aspnet-mvc-cascading-dropdownlist-with-jquery/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
