Home > AJAX, ASP.Net, Linq > AJAX Cascade DropdownList with Linq

AJAX Cascade DropdownList with Linq


Hi

try this example to create AJAX Cascade DropdownList with Linq :-

Step1 :-

Open SQL Server 2005 and create new database and create the following Tables :-

a) Country table :- 
– Id –> int (Primary Key ) and Auto increment
– Name –> nvarchar(20)

b) City table :-
– Id –> int (Primary Key ) and Auto increment
– Name –> nvarchar(20)
– Country_Id –> int (foreign key)

Step 2 :-

Open Visual Studio 2008 and create new website and add new DataContext class called “DataClasses.dbml”

and drag Country and City table inside it

Step 3 :-

Add new Web Service called “WebService” and  in WebServive.cs add the following code :-

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using AjaxControlToolkit;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues, string category)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        IEnumerable<CascadingDropDownNameValue> vals = null;
        short targetID = 0;
        vals = from tp in db.Countries
               select new CascadingDropDownNameValue
               {
                   name = tp.Name,
                   value = tp.Id.ToString(),
               };
        return vals.ToArray<CascadingDropDownNameValue>();
    }

    [WebMethod]
    public CascadingDropDownNameValue[] GetCities(string knownCategoryValues, string category)
    {
         DataClassesDataContext db = new DataClassesDataContext();
        IEnumerable<CascadingDropDownNameValue> vals = null;
        StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        short country_id;
        if (!kv.ContainsKey("Country") || !short.TryParse(kv["Country"], out country_id))
        {
            return null;
        }
        vals = from tp in db.Cities
               where tp.Country_Id == country_id
               select new CascadingDropDownNameValue
               {
                   name = tp.Name,
                   value = tp.Id.ToString(),
               };
        return vals.ToArray<CascadingDropDownNameValue>();
    }
}

Step 4 :-

Add new web page and script Manager control and two DropdownList control and two AJAX CascadingDropDown

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <table style="width: 50%;">
            <tr>
                <td>
                    Select Country :-</td>
                <td>
                    <asp:DropDownList ID="ddl_Country" runat="server">
                    </asp:DropDownList>
                    <cc1:CascadingDropDown ID="ddl_Country_CascadingDropDown" runat="server"
                        Enabled="True"
                        TargetControlID="ddl_Country"
                        LoadingText="Loding ..."
                       PromptText="Select Country"
                       ServiceMethod="GetCountries"
                       ServicePath="WebService.asmx"
                       Category="Country"
                      UseContextKey="True">
                    </cc1:CascadingDropDown>
                </td>
            </tr>
            <tr>
                <td>
                    Select City :-</td>
                <td>
                    <asp:DropDownList ID="ddl_City" runat="server">
                    </asp:DropDownList>
                    <cc1:CascadingDropDown ID="ddl_City_CascadingDropDown" runat="server"
                        Enabled="True"
                        ParentControlID="ddl_Country"
                        TargetControlID="ddl_City"
                        LoadingText="Loding ..."
                       PromptText="Select City"
                       ServiceMethod="GetCities"
                       ServicePath="WebService.asmx"
                       Category="City"
                      UseContextKey="True">
                    </cc1:CascadingDropDown>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Step 5 :-

In Code behind add the following code :-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using AjaxControlToolkit;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    // Country WebMethod
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetCountry(string knownCategoryValues, string category)
    {
        return new WebService().GetCountries(knownCategoryValues, category);
    }

    // City WebMethod
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetCity(string knownCategoryValues, string category)
    {
        return new WebService().GetCities(knownCategoryValues, category);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Hope this helps

Good Luck.

Advertisements
  1. October 13, 2010 at 7:46 am

    hi, very nice article. I have some troubles though.

    My second DDL is being populated with all subcategories, and not the ones that are associated with my category.

    heres is my linq
    vals = from f in db.ProductSubCategories
    where f.ProductCategory == f.ProductCategory
    select new CascadingDropDownNameValue
    {
    name = f.ProductSubCategoryName,
    value = f.ProductSubCategoryID.ToString(),

    };
    return vals.ToArray();

  2. yasserzaid
    October 14, 2010 at 8:14 pm

    @Klaus :- i can’t understand your question but you can apply this example as Category and SubCategory

    • Klaus
      October 17, 2010 at 7:05 pm

      That would be awesome. Thank you

  3. yasserzaid
    October 17, 2010 at 9:26 pm

    @Klaus :- Thanks alot for your comment hope my post helps you Good Luck 🙂

  4. November 17, 2011 at 7:38 am

    I have 3 of them and it doesn´t work. But the problem is in front of the computer. :-;

  5. diana
    April 30, 2013 at 9:40 am

    Greate post!!! Thank you very much!!! So easy and so good working!!!

    • yasserzaid
      April 30, 2013 at 8:38 pm

      @diana : you are welcome

  6. May 9, 2013 at 4:49 am

    Every weekend i used to pay a quick visit this website, as i want enjoyment, for the reason that this this site conations truly
    pleasant funny material too.

  7. May 12, 2013 at 12:04 pm

    I’ve been browsing online more than 2 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me.
    Personally, if all web owners and bloggers made good content as you did,
    the net will be much more useful than ever before.

  8. Paras
    August 11, 2014 at 11:38 am

    Hi.. I am getting Method Error 500 while using the code. Please advice on the error

    • yasserzaid
      September 17, 2014 at 9:11 am

      @Paras : Did you try this example and got Method Error 500 ?

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: