How to invoke a C # method from a JavaScript function?

1

I need to call a method c # from a JavaScript function ... at the moment the user tries to leave the page ... in such a case that my function can be as follows

window.addEventListener('unload', function(event) {
   // Invocar Metodo C# AQUI
});
    
asked by Efrain Mejias C 11.08.2016 в 15:16
source

2 answers

3

You could invoke a WebMethod to invoke functionality asynchronously to the server

Calling ASP.Net WebMethod using jQuery AJAX

As you will see in the article, use the $ .ajax

$.ajax({
    type: "POST",
    url: "CS.aspx/GetCurrentTime",
    data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function(response) {
        alert(response.d);
    }
});

defining in the code of the page

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

This way, in the javascript event that detects the change of page, it can invoke code in the server

    
answered by 11.08.2016 / 18:28
source
3

This can be done without JavaScript. If you have AutoEventWireup with value true (has value true by default, as indicated in the documentation of MSDN ), you can link the events to the event handler methods by putting "Page_" and the name of the event.

Thus, in the particular case of the event unload , you can define the controller directly in C # in this way, and it will be called when the event unload of the page is launched:

protected void Page_Unload(object sender, EventArgs e) {
    // tu código
}
    
answered by 11.08.2016 в 15:49