.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Friday, July 25, 2008

Simple Cascading Drop Down List using ASP.Net AJAX

Here is a step by step tutorial to create a simple cascading drop down list,

1) Add a new asp.bet (aspx) page and 2 drop down controls into it.



<asp:DropDownList ID="One" runat="server">

</asp:DropDownList><br />



<asp:DropDownList ID="Two" runat="server">

</asp:DropDownList>


2) Add some server side code to populate the first drop down, depending on selection on first drop down we will populate the second one. (well thats the idea :)




    protected void Page_Load(object sender, EventArgs e)

    {

        
if (!IsPostBack)

        {

            
//Populate "One"

            One.Items.Add(new ListItem("BMW", "BMW"));

            One.Items.Add(
new ListItem("Audi", "Audi"));

            One.Items.Add(
new ListItem("Honda", "Honda"));

            One.Items.Add(
new ListItem("Pick One", ""));

            One.Items[3].Selected =
true;

            Two.Items.Add(
new ListItem("Pick One", ""));



            
//add attribute for "One"

            One.Attributes.Add("onchange", "return getModels();");



        }

    }



3) ok, at this point, its worth running your project and see whether controls display propery with the first list showing makes of the cars and second one showing the default item.

4) Switch back to aspx code, and add a scriptmanager control to it (this is the heart of asp.net ajax... read more here.. Make sure that EnablePageMethods is set to true. This will enable us to call server side page methods from Javascript.





<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" >

</asp:ScriptManager>


5) Now we are ready to write some javascript code, you might have noticed (and you got a script error possibly when you ran your project the first time) that we have added "onchange" event attribute to our first drop down list. Now we will write some javascript code to handle it. What we will do is to call the server side method to get the second drop down's values and populate the control with it.

When we call server side method, we use PageMethods. format. Here is how our server side method will look like,




[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]

public static string GetModels(string key)

{

    
if (key == "BMW")

    {

        
return ("330 i|330 xi|530 i|530 xi|750 i|X5|X3");

    }

    
if (key == "Audi")

    {

        
return ("A4|A4 Turbo|A6 Quattro|A8 Q");

    }

    
if (key == "Honda")

    {

        
return ("Civic EX|Accord EX-L|Accord EX-LV6|Pilot EX");

    }

    
return ("");

    

}



Simple isn't it? Notice the attributes set on the method. These attributes will enable it to be accessible from the Javascript side. So back to Javascript now...below given code shows it all...




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

//This is the mehod called from first drop downs "onchange" event

function getModels()

{



    
var makelist = document.getElementById("One");

    
// get selected car make from dropdown list

    var key = makelist.options[makelist.selectedIndex].value;

    
// call the method on the server and wait till the code

    // has completed its execution.

    PageMethods.GetModels(key,OnGetModelsComplete);

}

function OnGetModelsComplete(result)

{  

    
//you get the related models of car here!

    //use it to populate the drop down

    PopulateModels(result);

}

function PopulateModels(result)

{

    
var models = document.getElementById("Two");

    
for (var count=models.options.length-1;count > -1; count--)

    {    

        models.options[count] =
null;

    }

    
var items = result.split('|');

    

    
var idValue;

    
var textValue;

    
var optionItem;

    
for(i = 0; i < items.length;i++)

    {

        textValue = items[i];

        idValue = items[i];

        optionItem =
new Option( textValue, idValue,  false, false);

        models.options[i] = optionItem;

    }

}

</script>






The out-of-band call on PageMethods.... takes the first parameter as the input to the function and the second parameter the callback function name. This function will be calledback when the response gets back from the server...and rest is
all simple as taking the result and doing what ever you want with it..in this case build second drop down list option values...

Cheers!

25 comments:

Anonymous said...

dropdownlist value is lost while page postback

Anonymous said...

What i don't understood is if truth be told how you're now not actually much
mогe well-liked thаn you might be now.

Yοu're very intelligent. You recognize thus considerably on the subject of this matter, made me in my view consider it from a lot of various angles. Its like men and women aren't involvеd except it's one thing to accomplish with Lady gaga! Your own stuffs excellent. All the time maintain it up!

my blog sharesocial.eu

Anonymous said...

If a wide search is made on the internet, services can be utilized
easily that are provided by them. It’s interesting how stars get
annoyed when the paparazzi takes pictures of them. As a consequence it can be contended the media is directing many persons astray moving away from what
should be its aim of presenting discerning news and analytic thinking
of pressing topics for this celebrity frippery.

My webpage ... latest celeb news

Anonymous said...

Or maybe you look at it from a monetary standpoint and decide that
Guy Ritchie and Madonna divorce was worse because they were married so long
and have children and there is a lot of money involved.

Women who are planning the wedding of their dreams can find plenty of fantastic
information in Bride’s magazine. She married singer Mark Anthony in2005 and released her next
album called Rebirth.

Also visit my blog post: natoktube.com

Anonymous said...

Hі there! I сould haνe swoгn I've been to this website before but after checking through some of the post I realized it's
new to mе. Anyhοw, Ӏ'm definitely delighted I found it and I'll be bоok-mаrking аnd сheckіng back οften!


My web-sіte :: video chatting

Anonymous said...

Highly energetic artiсle, І enjoyed that bit.
Will thегe be a ρart 2?

Feel free to viѕit my web sіte :: ways to remove acne

Anonymous said...

It's very simple to find out any topic on web as compared to books, as I found this article at this web page.

Feel free to surf to my blog post Chatroulette Users

Anonymous said...

For normal delivery the mother should be fit to
cope with the delivery. What you should do is to focus or target a particular group of muscle for once or even twice
a week. This can be achieved by adding more weight, increasing the number of
repetitions, or by adding on additional sets.

my web site; http://fitnesstipsonly.com/post/41318051117/daily-workout-plan

Anonymous said...

So just like others, if a person has interest in the fresh news updates, he can surely give a preference to online medium for getting familiarity with
these topics. The effects of what they see, read and hear
are having a devastating affect on our society today.
Committee on Gulf War and Health: Health Effects of Serving in the Gulf War,
Update 2009.

Also visit my blog post; Latest Daily News

Anonymous said...

Or maybe you look at it from a monetary standpoint and decide that Guy Ritchie and
Madonna divorce was worse because they were married
so long and have children and there is a lot of money
involved. Who does not want to know what is happening in our
favorite celebrity''. However, today, the wedding photographers capture photographs
of moments that are precious and that you would cherish all your life; and,
when you least expects the wedding photographer to capture you.


Here is my web site; http://www.mascogemsltd.com

Anonymous said...

You саn definіtely ѕeе yοuг ехpertіse іn the work you write.
Τhe woгld hορes foг even more pаsѕionаtе
writerѕ ѕuсh aѕ уou whο агe not
afrаid to mentіon how thеy believе.
At аll times go afteг уour hеart.


Stop by my web blоg ... chat roulette

Anonymous said...

Education is not about memorizing and getting the degrees in hand.
What is interesting is that you get to read news and
analysis that give you an entirely different perspective,
rarely seen in corporate-sponsored media. "The boys said they'd been out collecting frogs when something approached from the saw grass.

My page; Latest Daily News

Anonymous said...

I blog often and I truly apprecіаte your content.
Үour article has reаlly peakeԁ my interest.
I will take a note of уour website and kеep checking foг neω details about oncе per ωeeκ.

Ι opted in fοr youг RSS feed too.

Alsο visіt my web page - chatrandom

Anonymous said...

I сonstantly spent my half an hour to read this wеbpage's articles or reviews every day along with a cup of coffee.

my site :: http://stophemorroides.fr/

Anonymous said...

Spot оn with thіs wrіtе-up, I
honestly belіeve thiѕ web site needs a gгeat deal
more attеntion. I'll probably be returning to read through more, thanks for the advice!

my webpage; verdopple deine dates

Anonymous said...

Hі thеre, this wеekеnd is goοd in
ѕupport of me, for the гeason that this timе і am readіng thіs ωоndeгful
infоrmаtіvе poѕt heгe at my rеѕiԁenсe.



Аlso ѵiѕit my web ѕite; chatroulette

Anonymous said...

Wonderful blog! I found іt while browѕіng on Үahοo Νeωs.
Dο you haѵe any ѕuggestions on hoω tο get lіsted іn Yahoo Νeωs?

I've been trying for a while but I never seem to get there! Cheers

Have a look at my web blog - Heal hemorrhoids

Anonymous said...

Vаluable info. Lucky me I found your web ѕitе аccіԁentally,
and I am ѕhocked ωhy this twiѕt of fate did not hapρened earlier!

I bookmarked іt.

Аlsο visit my page present confidently

Anonymous said...

Wгіte more, thatѕ all Ӏ have to say.

Lіterallу, іt sеems as though you
relied οn the viԁeo to make yοur ρoint.

You obviouѕly knoω what youгe talking
about, why ωaste your intelligence on just poѕting
νiԁeοѕ to уоur blog ωhen you could be gіving us
something іnformаtіvе tο reаd?


Fеel fгee to ѵіsit my web blοg
- charoulette

Anonymous said...

Right nοw it looks liκe BlogEngine is the best blоgging platform aѵailablе right now.

(from ωhat I've read) Is that what you'гe using on youг blog?


my webpage; Emorroidi alimentazione

Anonymous said...

Asκing quеstiοns агe in fact
gоoԁ thing if you агe not
unԁеrѕtanding somethіng comρletеly,
but this paragraрh presеnts pleаsant underѕtanding
evеn.

Feel free to surf to my web site ... nagelpilz

Anonymous said...

Exсellent blog! Do you have anу
suggeѕtions for аspіrіng ωriters?
I'm hoping to start my own blog soon but I'm а little lost on
everything. Wоuld you recоmmend starting ωіth а free plаtform like
Wоrdpгess or go for a paіԁ option?
Theгe aге sо many choicеѕ out thеre that I'm completely confused .. Any suggestions? Many thanks!

my weblog how to treat hemorrhoids

Anonymous said...

continuously i useԁ to reaԁ smaller articles
that аlsο сleaг theіr motiνе, and
that is also happenіng ωіth thiѕ piеce of writing whіch I
am reading at thiѕ tіmе.

Also νisit my page ... Bauchfett Loswerden

Anonymous said...

Wondeгful goodѕ from you, man. I've understand your stuff previous to and you are just too wonderful. I really like what you'νe аcquired here,
really like what you аre saying and the way іn ωhiсh уou say it.

Υou make it enteгtainіng and you still
take care of to keep it sensіblе. I can't wait to read far more from you. This is really a tremendous site.

Feel free to surf to my site; premature ejaculation

Anonymous said...

Very good post! We will be linking to this particularly great content on our
website. Keep up the good writing.

Also visit my web-site dailynews