0

基本上我试图做推荐的事情,但不知何故它不起作用。问题是我无法将下拉列表中选定项目的值设为文本框值。我观察到的是 JS 代码没有被触发。可能是什么问题呢?

我的代码是;

HTML

                <div class="dropdown show col-md-2 p-1">
                    <a class="btn btn-secondary btn-sm dropdown-toggle p-1" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" runat="server">Load Evaluation
                    </a>

                    <div id="dropdown"  runat="server" class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                    </div>

                </div>

                <div>
                    <asp:TextBox ID="dropLabel" runat="server" AutoPostBack="true" OnTextChanged="dropLabel_OnTextChanged" Style ="display:block"></asp:TextBox>
                    
                </div>

JS

$('#dropdown a').on('click', function () {

$('#dropLabel').val(this.text());
sessionStorage.setItem('label1', $(this).text());
location.reload(true);

})

C#

    protected void dropLabel_OnTextChanged(object sender, EventArgs e)
    {
        var labelText = (sender as TextBox).Text;
        //... do something with the text.

        A3toSqlDataContext ctx4 = new A3toSqlDataContext();
        var yukle = from c in ctx4.A3_Coaching
                    where c.name == labelText
                    select c;

C# 用于标记,包括

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            A3toSqlDataContext ctx = new A3toSqlDataContext();
            var alp = from c in ctx.A3_Coaching
                      select c.name;

            foreach (var item in alp)
            {

                HtmlGenericControl anchor = new HtmlGenericControl("a");
                anchor.Attributes.Add("href", "#");
                anchor.InnerHtml = Convert.ToString(item);
                anchor.Attributes.Add("class", "dropdown-item");


                dropdown.Controls.Add(anchor);

            }

        }




    }
4

1 回答 1

0

问题是,您dropLabel可能是服务器端控件,但实际的 javascript 发生在客户端上,因此您的 asp.net 应用程序在您回发到服务器之前不会意识到这一点。

你应该能够做到这一点,如果你将你转换droplabel为一个不可见Textbox的,当它的文本发生变化时,它会为你做一个回发:

<div>
    <asp:Textbox id="dropLabel" runat="server"
               AutoPostback="true"
               OnTextChanged="dropLabel_OnTextChanged"
               style="display:none">
    </asp:Textbox>
</div>

代码隐藏:

protected void dropLabel_TextChanged(object sender, EventArgs e)
{
     var labelText = (sender as TextBox).Text
     //... do something with the text.
} 

确保您检查 PostBackPage_Load以不重新加载所有内容并可能使用覆盖您的状态if(!IsPostBack) { /*... do regular Page_Load*/}

于 2021-02-14T19:19:48.827 回答