Redirecting from ASP.NET Dropdown

10,291

Solution 1

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>

Solution 2

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);
Share:
10,291
Donald
Author by

Donald

Updated on June 28, 2022

Comments

  • Donald
    Donald almost 2 years

    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?