Click here to Skip to main content
12,350,035 members (25,803 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# ASP.NET
How to call c# (code behind )function from java script
public void add()
{
int a=1;
int b = 3;
int c = a+b;
}
how to call it from java script
<script type="javascript">
// code here 
</script>
Posted 15-Jan-13 4:37am
Edited 15-Jan-13 5:54am
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Can you give this a shot?

$('#IdOfAButtonOrSomething').click(function()
{
	var dataToSend={Send1:'Value1',Send2:'Value2', Method:'Add' };
 
		var opts =
		{
			url: '<%=ResolveUrl("~/YourCodeBehindFile.aspx") %>',
			data: dataToSend,
			dataType: 'JSON',
			type: 'POST',
			success: function (response) {
				//Do something here if successful
			}
		}
		$.ajax(opts);
});

This would be in your code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (Request.Form["Method"] == "Add")
        {
            add();
            return;
        }
    }
}
 
public void add()
{
    int a=1;
    int b = 3;
    int c = a+b;
}
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

What I got from your question is that you want to call a Server side Method(s) from your JavaScript.

For this you need to use jQuery, which uses Ajax call to call a Method from Server side.

Refer the Following link & you will come to know how to Call a Server side method from your JavaScript.

Click Here

Read & get any doubt feel free to ask.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

An easy way is to have a hidden ASP button on your web page with the Click property pointed to your Code-behind function (in this case, add()), which you can then trigger with a simple Javascript call.

CSS:

<style type="text/css">
    .no-display
    {
    display:none;
    }
</style>


ASP:

<asp:Button CssClass="no-display" ID="myBtn" runat="server" OnClick="add" useSubmitBehavior="false" />


Plain Javascript:

document.getElementById('myBtn').click();

JQuery:
$("[id*='myBtn']").click();
  Permalink  
v2
Comments
nika2008 19-Jan-13 6:23am
   
i have suggestion never don`t do this way never
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

There are few ways to interact with server side through client side(Javascript):
1. XMLHttpRequest[^]
2. Callback[^]
3. WebService call[^]
4. PageMethod[^]

Try that you find fit.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160621.1 | Last Updated 19 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100