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

3

I have a button and I wanted to program click of it, and when I use <asp:Button> I program click of it in code behind . I'm now using a button normal.

I know almost nothing about JavaScript and wanted to program it in code behind as well. Would I have created a JavaScript function by calling a C # method?

    
asked by anonymous 11.09.2015 / 20:51

4 answers

1

Step 1, on the server-side add method.

[WebMethod]
public static string Message(){
     return " MENSAGEM ";
}

Step 2, search for the <asp:ScriptManager ID="..." runat="server" /> tag and add EnablePageMethods="true"

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

Step 3, let's create a method in javascript

function getMessage() {
    PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
}

Step 4, let's use a normal button ...

<input type='submit' value='Get Message' onclick='getMessage();return false;' />
    
11.09.2015 / 21:05
3

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.
  }
});
    
11.09.2015 / 21:04
3

Yes. You will need AJAXExtensionsToolbox in your project.

First, put the following on your page:

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

In Code Behind , create the static method:

using System.Web.Services;

[WebMethod]
public static string MeuMetodo(string nome)
{
    return "Oi, " + nome;
}

To call, you can do this:

<script type="text/javascript">
    $("#botao").click(function () {
        PageMethods.MeuMetodo("Cigano Morrison Mendez");
    });
</script>

For example, I assume you have jQuery in your project.

    
11.09.2015 / 21:03
1

Directly is impossible but ASP.Net has facilities for calling the client invoking what they need:

<asp:Button ID="botao" OnClick="botao_Click" runat="server" />

Then in Code-behind :

protected void botao_Click(object sender, EventArgs e) {
   //faça o que quer aqui
}
    
11.09.2015 / 20:58