Home » Questions » Computers [ Ask a new question ]

Call ASP.NET function from JavaScript?

Call ASP.NET function from JavaScript?

"I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.

Is it possible to call a method I created in ASP with JavaScript's click event?"

Asked by: Guest | Views: 102
Total answers/comments: 4
Guest [Entry]

"Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):

It is a little tricky though... :)

i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like

public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}

ii. This should add (using Tab-Tab) this function to your code file:

public void RaisePostBackEvent(string eventArgument) { }

iii. In your onclick event in JavaScript, write the following code:

var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);

This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.

P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!"
Guest [Entry]

"The __doPostBack() method works well.

Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.

<div style=""display: none;"">
<asp:Button runat=""server"" ... OnClick=""ButtonClickHandlerMethod"" />

From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.

var button = document.getElementById(/* button client id */);

Guest [Entry]

"The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.

I suggest the Microsoft AJAX library. Once installed and referenced, you just add a line in your page load or init:


Then you can do things like:

<Ajax.AjaxMethod()> _
Public Function Get5() AS Integer
Return 5
End Function

Then, you can call it on your page as:


The last parameter of your function call must be the javascript callback function that will be executed when the AJAX request is returned."
Guest [Entry]

You can do it asynchronously using .NET Ajax PageMethods. See here or here.