Call jQuery from ASP.NET server side

In this post, I will explain you that how can you call jQuery from server side in ASP.Net. Lets place a button on the page and on click of button, server side click event of button will get executed.

<asp:Button ID="btnCall" runat="server" Text="Call jQuery From Server"
OnClick="btnCall_Click" />

Server side click event of button.

protected void btnCall_Click(object sender, EventArgs e)
{
   StringBuilder strScript = new StringBuilder();
   strScript.Append("$(document).ready(function(){");
   strScript.Append("alert('I am called from server.');");
   strScript.Append("});");
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Script",
strScript.ToString(), true);
}

As you can see, I have registered the jQuery script using RegisterStartupScript method. So now when button click code is finished, you will see an alert on the page.

However, if you are working with ajax and your button is placed with in an updatepanel, above code will not work. Well, you can try yourself.

Call jQuery from ASP.NET server side, If Ajax is used.

Lets place a button within update panel.

<asp:ScriptManager ID="sm1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="updPnl" runat="server">
   <ContentTemplate>
       <asp:Button ID="btnCallAjax" runat="server" 
                Text="Call jQuery From Server Within Ajax"
onclick="btnCallAjax_Click"/>
     </ContentTemplate>
</asp:UpdatePanel>

Server side click event of button.

protected void btnCallAjax_Click(object sender, EventArgs e)
{
    StringBuilder strScript = new StringBuilder();
    strScript.Append("$(document).ready(function(){");
    strScript.Append("alert('I am called from server within Ajax.');");
    strScript.Append("});");
    ScriptManager.RegisterStartupScript(updPnl, updPnl.GetType(),"Script",
strScript.ToString(), true);
}

You need to use ScriptManager.RegisterStartupScript method to register your jQuery script, if your postback is asynchronous.

Feel free to contact me in case of any query. I will gladly help you.



Responsive Menu
Add more content here...