Call C# method using JavaScript

Title

 

Call C# method using JavaScript

Introduction

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.

Default.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
 <script>
 function myTest() {
 if (confirm("Do you want to Add two numbers?") == true) {
 <%= Page.ClientScript.GetPostBackEventReference(btnAdd, String.Empty) %>;
 }
 else {
 return false;
 }
 }
 </script>
</head>
<body>

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

<div>

<table>

<tr>

<th>Number A:</th>


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

 </tr>


<tr>

<th>Number B:</th>


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

 </tr>


<tr>

<th>Total:</th>


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

 </tr>

 </table>

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

 </form>

</body>
</html>

Default.aspx.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

&nbsp;

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

{

protected void Page_Load(object sender, EventArgs e)

{

&nbsp;

}

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