How to pass values from Javascript to code behind code function?

Posted by Only4ram under ASP.NET on 2/10/2015 | Points: 10 | Views : 2629 | Status : [Member] | Replies : 3

Please explain in detail that how to pass parameter values from javascript to c#.code function?

For example:

When i click button i need to call this function through javascript and pass values for x and y should be from javascript...

public void Add(int x,int y)
int k=x+y;


Posted by: Nandkishorrech on: 2/16/2015 [Member] Starter | Points: 25

You can pass the values using below code

var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;

here demo is label control.

Only4ram, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: A2H on: 2/22/2015 [Member] [MVP] Bronze | Points: 25

You can use the PageMethods to call server side function (C#) from ClientSide(Javascript)

Please try the below implementation

1) Add a script Manager to your page and set the 'EnablePageMethods' property of script manager to True.

<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"/>

2) Add Javascript function to the body section of page


<form id="form1" runat="server">
<script type="text/javascript">
function CallingServerSideFunction() {

3) Change you method like given below

  //Please note that the method should be a Static and WebMethod.

public static void Add(int x, int y)
int k = x + y;

//Your Logic comes here

4) Calling the Javascript function

<input id="Button2" type="button" value="FunctionCall" onclick="CallingServerSideFunction()" />

Please mark my reply as answer if it helps to resolve your problem

Only4ram, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response