views:

1412

answers:

5

What's the best method for handling a situation where you have an ASP.Net Dropdownlist that is used to link to another URL

edited for clarity

Here's the basic scenario:

Dropdownlist with 5 cities bound to it

Selecting one of the cities should send me to a URL based on the city

Right now I am posting back using the "OnSelectedIndexChanged" event then handling the event and redirecting to the appropriate page.

However this is causing 2 hits to the server per city selected, 1 to handle the postback and redirect, then another to render the actual page.

Is using custom javascript to construct a URL my best option?

+3  A: 

Set the autopostback to false, and add this to the onchange client-side event (assuming the value has the entire URL, if not, edit as appropriate):

window.navigate(this.options[this.selectedIndex].value);
Robert C. Barth
+12  A: 

You can add a client-side handler for the selection changed event and then redirect to the desired page based on the selected value:

<asp:DropDownList ID="ddl" runat="server"
  onchange="javascript:document.location.href = this.value;" >
    <asp:ListItem Text="a" Value="http://url1"&gt;&lt;/asp:ListItem&gt;
    <asp:ListItem Text="b" Value="http://url2"&gt;&lt;/asp:ListItem&gt;
    <asp:ListItem Text="c" Value="http://url3"&gt;&lt;/asp:ListItem&gt;
    <asp:ListItem Text="d" Value="http://url4"&gt;&lt;/asp:ListItem&gt;
</asp:DropDownList>
M4N
It is cool that you didn't have to resort to <%=ddl.ClientID %> anywhere!
jrcs3
very nice, I never realized "this" would work in that context. I would have written it as a "document.getElementById('ddl')..."
rally25rs
if you are mention the object that you are calling the script from ... always use "this" keyword :)
balexandre
Little remark: the "javascript:" part is not necessary and even considered useless by many, especially if you're already in a JS event handler like "onchange".
awesome and easy code to navigate to different url.
fzshah76
A: 

I just wonder, why not fetching the city information via AJAX (there are several video tutorials on www.asp.net/learn) and show the user the city information instead of create other more page jump?

it is only an idea, a Web 2.0 idea :)

balexandre
A: 

If the page is heavy and you are concerned about render times, you can use ajax to render the query results. The server hit to process the post data and redirect should be minimal and not worth doing it client side. Personally, I'd concentrate more on displaying the data the user wants the first time.

A: 

Normally, I would agree, but there are needs to have a concrete URL for each page + regenerating other parts of the page on hitting the URL as well.

Thanks for the suggestions though!

Donald