ASP.在用户控件中单击. NET on按钮,使用javascript在主页面设置文本框的值

ASP.NET on button click in user control set the value of a textbox in the main page using javascript

本文关键字:主页 javascript 使用 置文本 控件 用户 单击 NET 按钮 on ASP      更新时间:2023-09-26

net/c#应用程序,我有一个包含按钮的用户控件。

我在运行时将控件加载到主页面的PlaceHolder中。

<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>

背后的代码:

MyControl CC = (MyControl)LoadControl("Controls/MyControl.ascx");
PlaceHolder1.Controls.Add(CC);
在主页上我有一个文本框和一个链接按钮。我想做以下事情:

当用户单击用户控件中的按钮时,文本框的值被设置为'5',并且使用javascript触发链接按钮单击事件。

我尝试了以下操作,但没有成功:

在主页:

<asp:TextBox ID="PageBox" runat="server"></asp:TextBox>
<asp:LinkButton ID="LinkButtonPage" runat="server" onclick="LinkButtonPage_Click" Text="Submit"></asp:LinkButton>

在用户控件中:

<script type="text/javascript">
    function SetPage(a) {
        var txtFld = document.getElementById("PageBox");
        txtFld.value = a;
        document.getElementById('LinkButtonPage').click();
        return false;
    }
</script>
<input type="button" id="Button1" onclick="SetPage('5');" value="Submit"/>

但是当我点击按钮时什么也没发生。

感谢您的帮助

您正在获得控件的id错误。你应该这样做:

 document.getElementById('<%=PageBox.ClientID%>');

 document.getElementById('<%=LinkButtonPage.ClientID%>');

还需要将JavaScript函数移动到主页面,因为主页面包含两个控件的引用。

如果您想在更改文本框值后提交页面,请尝试:

<script type="text/javascript">
    function SetPage(a) {
        var txtFld = document.getElementById("<%=PageBox.ClientID%>");
        txtFld.value = a;
        document.forms[0].submit(); // or document.forms['formname'].submit()
        return false;
    }
</script>

我通过直接在按钮的onclick事件中添加函数来修复这个问题

<input type="button" id="Button1" onclick="document.getElementById('PageBox').value='5';document.getElementById('LinkButtonPage').click();return false;" value="Submit"/>