在asp中弹出消息框,javascript无法识别?

时间:2012-08-09 11:30:57

标签: c# javascript asp.net

我遇到了一个消息框用户控件的问题。我想要一个可以给出消息的控件,用户可以通过单击按钮来解除,该按钮可以插入到许多地方。 我已经将javascript应用到了消息框控件中,希望我可以将消息集集中在一起,但是当浏览到添加了消息框控件的页面时,我会收到此错误:

CS1061: 'ASP.components_messagebox_ascx' does not contain a definition for 'HideBox' and no extension method 'HideBox' accepting a first argument of type 'ASP.components_messagebox_ascx' could be found

控制如下:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Messagebox.ascx.cs" Inherits="FosterNetwork.Components.Messagebox" %>
<script type="text/Javascript">
    function HideBox() {
        document.getElementById("PNL_Messagebox").setAttribute("visible", false);
    }
</script>
<asp:Panel ID="PNL_Messagebox" runat="server">
    <asp:Label ID="LBL_Message" runat="server" />
    <asp:Button ID="BTN_Ok" Text="Ok" OnClick="HideBox()" runat="server" /> <!--Error happens on this line-->
</asp:Panel>

我相当肯定我做得对,但显然我做错了,如果不行的话。对情况的任何启示都是宏伟的。

附录:如果我注释掉Button控件,页面加载正常,脚本也加载正常(查看页面源)

2 个答案:

答案 0 :(得分:1)

Onclick查找服务器端功能,而不是javascript。或者,将您的按钮定义为<input type='button' onclick='HideBox'或将当前代码更改为:

<script type="text/Javascript">
function HideBox() {
    document.getElementById("<%= PNL_Messagebox.ClientID %>").setAttribute("visible", false);
    return false;
}
</script>
<asp:Button ID="BTN_Ok" Text="Ok" OnClientClick="return HideBox()" runat="server" />

OnClientClick中返回false,阻止asp按钮回发。

编辑:正如Monty所说,您的面板控件的客户端ID未在您的代码中正确设置。

答案 1 :(得分:1)

您引用的控件ID不是客户端ID,而是服务器ID。因此,检索&#39; ClientID&#39;从JavaScript函数中的控件开始,使用&#39; OnClientClick&#39;显示JavaScript消息的属性。

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Messagebox.ascx.cs" Inherits="FosterNetwork.Components.Messagebox" %>
<script type="text/Javascript">
    function HideBox() {
        document.getElementById("<%= PNL_Messagebox.ClientID %>").setAttribute("visible", false);
    }
</script>
<asp:Panel ID="PNL_Messagebox" runat="server">
    <asp:Label ID="LBL_Message" runat="server" />
    <asp:Button ID="BTN_Ok" Text="Ok" OnClientClick="HideBox()" runat="server" /> <!--Error happens on this line-->
</asp:Panel>