Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to call c# (code behind )function from java script
C#
public void add()
{
int a=1;
int b = 3;
int c = a+b;
}

how to call it from java script
JavaScript
<script type="javascript">
// code here 
</script>
Posted
Updated 15-Jan-13 5:54am
v2

Can you give this a shot?

C#
$('#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

C#
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;
}
 
Share this answer
 
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.
 
Share this answer
 
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:

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



ASP:

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



Plain Javascript:

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


JQuery:
JavaScript
$("[id*='myBtn']").click();
 
Share this answer
 
v2
Comments
nika2008 19-Jan-13 6:23am    
i have suggestion never don`t do this way never
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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900