Question

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?

Was it helpful?

Solution

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="document.location.href = this.value;" >
    <asp:ListItem Text="a" Value="http://url1"></asp:ListItem>
    <asp:ListItem Text="b" Value="http://url2"></asp:ListItem>
    <asp:ListItem Text="c" Value="http://url3"></asp:ListItem>
    <asp:ListItem Text="d" Value="http://url4"></asp:ListItem>
</asp:DropDownList>

OTHER TIPS

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);

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 :)

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.

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top