Call C# method using JavaScript



Call C# method using JavaScript


In this post we’ll see how to call C# method using JavaScript. But first question arises why we need such approach if we can directly call C #method using ASP controls?

So let’s consider a scenario in which we are required to perform client side operation (say for example validation) and if everything seems to be fine then move on to server for further processing. If we directly go to server and perform validation it will not cost server tripping and time, also it’s not a good coding practice to perform simple validations at server side.

In this example I’ll be adding two numbers and before adding I’ll take confirmation from user. If user selects yes then we’ll trigger C# method else control will stay at client side.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
 function myTest() {
 if (confirm("Do you want to Add two numbers?") == true) {
 <%= Page.ClientScript.GetPostBackEventReference(btnAdd, String.Empty) %>;
 else {
 return false;

<form id="form1" runat="server">




<th>Number A:</th>

<td><asp:TextBox ID="txtNumberA" runat="server"></asp:TextBox></td>



<th>Number B:</th>

<td><asp:TextBox ID="txtNumberB" runat="server"></asp:TextBox></td>




<td><asp:TextBox ID="txtSum" runat="server"></asp:TextBox></td>



 <asp:Button ID="btnAdd" runat="server" Text="Add" OnClientClick="myTest(); return false" OnClick="btnAdd_Click" />




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;


public partial class _Default : System.Web.UI.Page


protected void Page_Load(object sender, EventArgs e)




protected void btnAdd_Click(object sender, EventArgs e)


int a = Convert.ToInt16(txtNumberA.Text);

int b = Convert.ToInt16(txtNumberB.Text);

int c = a + b;

txtSum.Text = c.ToString();



Below line of code will be used to call C# method.

<pre><%= Page.ClientScript.GetPostBackEventReference(btnAdd, String.Empty) %>;</pre>

Keep visiting for more updates.

JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar