Is it possible for a JavaScript function to call a method that is in the code behind page?

Question:

I have a button and I want to program its click , and when I use an <asp:Button> I program its click in code behind . I am now using a normal button .

I know next to nothing about JavaScript and wanted to program it in code behind too. How would I create a JavaScript function calling a C# method?

Answer:

If your implementation is restricted to an ASP.NET page with codebehind, you can implement a call to a WebMethod as follows:

Mark the method as a WebMethod . It must necessarily be a static method.

public partial class _Default : Page 
{
  [WebMethod]
  public static string MetodoASerChamado()
  {
    return DateTime.Now.ToString();
  }
}

Call the function directly from the javascript implementation.

$.ajax({
  type: "GET",
  url: "Default.aspx/MetodoASerChamado",
  success: function(msg) {
    // Do something interesting here.
  }
});
Scroll to Top