How to pass the SelectedValue from a DropDownList as a query string in a LinkButton with/without using CodeBehind in ASP.net C#

StackOverflow https://stackoverflow.com/questions/21308907

Question

I've been fiddling with this issue for quite sometime now where I am not able to pass the value of a DropDownList to a Link Button. The Eval doesn't seem to work at all. Here's the code:

<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl='<%# string.Format(~/DataView.aspx?id=) + Eval(DropDownList1.SelectedValue) %>' Text="New ECRS"></asp:LinkButton>

When I run the above code, the link button doesn't function and there's no page redirection. But I see in many forums that people have given the above code as the answer. Am I doing something wrong? Thanks in advance :)

Was it helpful?

Solution

You could use Response.Redirect in the code behind instead:

<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton_Click" Text="New ECRS"></asp:LinkButton>

And in your code-behind:

void LinkButton_Click(Object sender, EventArgs 
{
   Response.Redirect("~/DataView.aspx?id=" + DropDownList1.SelectedValue, true);
}

OTHER TIPS

LinkButton is meant to do a postback to your page. It sounds like you want to link to a new page in which case you should just use HyperLink. Also your PostBackUrl content looks a bit strange:

<asp:HyperLink NavigateUrl='<%# string.Format("~/DataView.aspx?id={0}", DropDownList1.SelectedValue) %>' Text="Click here" />

Also, don't forget to DataBind the control or page otherwise the <%# %> part wont do anything.

Try using Jquery instead. See my code below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>
        $(document).ready(function() {
            $('#<%=DropDownList1.ClientID%>').bind('change', function(e) {
            $('#<%=HyperLink1.ClientID%>').attr("href", "DataView.aspx?id=" + $(this).val())
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Selected="True" Text="One" Value="One"> </asp:ListItem>
            <asp:ListItem  Text="Two" Value="Two"> </asp:ListItem>
        </asp:DropDownList>

        <asp:HyperLink ID="HyperLink1" NavigateUrl="DataView.aspx?id=One" runat="server">New ECRS</asp:HyperLink>
    </div>
    </form>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top