In this article I will explain with an example, how to call Server Side event from Client Side using JavaScript and jQuery in ASP.Net using C# and VB.Net.
Call Server Side event from Client Side using JavaScript
HTML Markup
The following HTML Markup consists of an ASP.Net Button and an HTML Anchor Link element. The HTML Anchor Link element has been assigned a Click event handler which makes call to the CallButtonEvent JavaScript function.
Inside the CallButtonEvent JavaScript function, the ASP.Net Button is referenced and its JavaScript Click function is called, which causes PostBack and the Server Side click event of the ASP.Net Button is called.
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<hr />
<a id = "lnk" href = "javascript:;" onclick = "CallButtonEvent()">Call Button Event</a>
<script type="text/javascript">
function CallButtonEvent() {
document.getElementById("<%=btnSubmit.ClientID %>").click();
}
</script>
Server Side Button Click event
Inside the following event handler, a JavaScript Alert Message is displayed using ClientScript.RegisterStartupScript function.
protected void Submit(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Button clicked.');", true);
}
Call Server Side event from Client Side using jQuery
HTML Markup
The following HTML Markup consists of an ASP.Net Button and an HTML Anchor Link element. The HTML Anchor Link element has been assigned a jQuery Click event handler.
Inside the jQuery Click event handler, the ASP.Net Button is referenced and its JavaScript Click function is called, which causes PostBack and the Server Side click event of the ASP.Net Button is called.
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<hr />
<a id="lnk" href="javascript:;">Call Button Event</a>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#lnk").click(function () {
$("[id*=btnSubmit]").click();
});
});
</script>
Server Side Button Click event
Inside the following event handler, a JavaScript Alert Message is displayed using ClientScript.RegisterStartupScript function.
protected void Submit(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Button clicked.');", true);
}
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads