後台代碼
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.')");}