代码改变世界

Call JavaScript With Jquery In Server-Side

2009-11-05 13:48  敏捷的水  阅读(330)  评论(0编辑  收藏  举报
后台代码
private string getjQueryCode(string jsCodetoRun)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("$(document).ready(function() {");
    sb.AppendLine(jsCodetoRun);
    sb.AppendLine(" });");

    return sb.ToString();
}

 

private void runjQueryCode(string jsCodetoRun)
{

    ScriptManager requestSM = ScriptManager.GetCurrent(this);
    if (requestSM != null && requestSM.IsInAsyncPostBack)
    {
        ScriptManager.RegisterClientScriptBlock(this, 
                                                typeof(Page), 
                                                Guid.NewGuid().ToString(), 
                                                getjQueryCode(jsCodetoRun), 
                                                true);
    }
    else
    {
        ClientScript.RegisterClientScriptBlock(typeof(Page), 
                                               Guid.NewGuid().ToString(), 
                                               getjQueryCode(jsCodetoRun), 
                                               true);
    }
}

前台代码

<asp:ScriptManager ID="sm" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="upPnl" runat="server">
    <ContentTemplate>
        <asp:Button ID="btnPostback" runat="server" 
                    Text="Standard Postback" 
                    OnClick="btnPostback_Click" />
        <asp:Button ID="btnAsynchPostback" runat="server" 
                    Text="Asynchronous Postback" 
                    OnClick="btnAsynchPostback_Click" />
    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="btnPostback" />
    </Triggers>
</asp:UpdatePanel>

 

调用示例

同步

protected void btnPostback_Click(object sender, EventArgs e)
{
    runjQueryCode("alert('After a standard postback.')");
}
异步
protected void btnAsynchPostback_Click(object sender, EventArgs e)
{
    runjQueryCode("alert('After an asynchronous postback.')");
}