从usercontrol调用时,jquery函数不起作用

时间:2012-07-06 00:15:00

标签: c# jquery asp.net user-controls

我有一个包含2个用户控件的aspx页面

UC1:编辑页面 - 包含编辑或数据输入字段。

UC2:通知页面 - 它有一个带有jquery功能的简单消息框

在我的aspx中我有这个功能:

public void ShowMessage(string status, string message)
    {
        Notification1.Message = message; //this is my user control UC2
        Notification1.Status = status;
        Notification1.DataBind();
    }

现在,当我的aspx页面需要显示消息时,这工作正常,但是当我希望用户控件1显示消息(无效字段或错误数量)时,它不会执行任何操作。现在它被调用,但jquery只是没有对它作出反应。

在UC2 -notification用户控件中这就是我所拥有的:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
<script type="text/javascript">
function showMsg(classname) {
    $("#MsgBox").attr('class', classname);
    $("#MsgBox").show().delay(5000).fadeOut();
}
</script>
<div id="MsgBox" class="info"><asp:Label ID="lblMessage" runat="server" /></div>

代码隐藏

 public string Status{ get; set; }
    public string Message { get; set; }
    public override void DataBind()
    {
        if (Message != string.Empty)
        {

            lblMessage.Text = Message;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
        }

    }

这就是我如何将用户控件中的函数调用到aspx页面:

((myaspxpage)this.Page).ShowMessage("error", "This is my error message.");

任何帮助将不胜感激!如果需要进一步的细节,请告诉我..提前致谢。

**编辑:我尝试将jquery和消息框放在我的编辑页面中以查看它是否会以这种方式工作而它不会这样看起来jquery在用户控件中运行不正常?

2 个答案:

答案 0 :(得分:0)

DataBind()方法的代码移至OnPreRender。这应该工作。原因是您不知道页面循环步骤(init,load,bind,...)将改变Message属性的代码。

就像你的情况一样,你似乎有一个按钮点击事件,你正在设置Message属性。这太晚了,因为你的Notification1控件已经是数据绑定。

将其作为最新阶段使其成功:

protected override void OnPreRender()
    {
        if (Message != string.Empty)
        {

            lblMessage.Text = Message;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
        }

    }

答案 1 :(得分:0)

我发现错误是我在aspx页面中调用该函数的按钮是在更新面板中,我需要添加一个触发器事件以使其工作..感谢大家的帮助它是更新面板导致错误:(