簡體   English   中英

如何使用/不使用ASP.net C#中的CodeBehind將DropDownList中的SelectedValue作為查詢字符串傳遞給LinkBut​​ton

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

我已經在這個問題上擺弄了一段時間,無法將DropDownList的值傳遞給鏈接按鈕。 評估似乎根本不起作用。 這是代碼:

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

當我運行上面的代碼時,鏈接按鈕不起作用,並且沒有頁面重定向。 但是我在許多論壇上看到人們已經給出了上面的代碼作為答案。 難道我做錯了什么? 提前致謝 :)

您可以在后面的代碼中使用Response.Redirect:

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

並且在您的代碼背后:

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

LinkBut​​ton旨在回發到您的頁面。 聽起來您想鏈接到新頁面,在這種情況下,您應該只使用HyperLink。 另外,您的PostBackUrl內容看起來有些奇怪:

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

另外,不要忘記對控件或頁面進行DataBind操作,否則<%#%>部分不會做任何事情。

嘗試改用Jquery。 請參閱下面的代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM