The Talking Walnut The Talking Walnut - 29 days ago 11
ASP.NET (C#) Question

asp.net dropdown list postback to anchor

How can I go to an anchor tag on the page when the myDropDownList_SelectedIndexChanged() event fires?
I am using regular ASP.NET Forms.

Update: The following is valid for an ASP.NET Button. I would like to achieve the same functionality (going to #someAnchor) when I select an option from the Dropdown list.

<asp:Button ID="btnSubmit" runat="server" Text="Do IT" Width="186px" PostBackUrl="#myAnchor" CausesValidation="false" />


Update: I will try to further explain details that I didn't cover in enough detail initially.
This is a long page and in the middle of the page there is a dropdown list. Below the dropdown list is a label that will change based on the item selected from the dropdown. The update of the label will occur during the postback. At this point the page needs to remain focused on the dropdown. I tried to use AJAX to accomplish this, but other implementation details prevent that from working. The ability to go to an anchor tag after the postback would be a simple solution. Here is a simplified version of what I am trying to accomplish.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub myDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
myLabel.Text = myDropDown.SelectedValue
'When this finishes, go to #myAnchor
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Imagine many lines of text here.
<a name="myAnchor"></a>
<asp:DropDownList ID="myDropDown" runat="server" OnSelectedIndexChanged="myDropDown_SelectedIndexChanged" asdf="asdf" PostBackUrl="#myAnchor"></asp:DropDownList>
<asp:Label ID="myLabel" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

Answer

Here is what I have implemented to accomplish my desired result.

Protected Sub myDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myDropDown.SelectedIndexChanged

    Response.Redirect("Default.aspx?myDropDown=" & myDropDown.SelectedItem.Text.ToString.Trim & "#myAnchor")

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim myDropDownValue As String = Request.QueryString("myDropDown")
        If myDropDownValue <> "" Then

            myDropDown.Items.FindByText(myDropDownValue).Selected = True
                Label1.Text = GetTextBasedOnDropDownSelection(myDropDownValue)

        End If
    End If
End Sub
Comments