简体   繁体   中英

Calling c# events from javascript code

你可以告诉我是否可以从ASP.NET Web应用程序中的javascript代码调用C#事件或方法?

You cannot directly execute a C# Event or Method. You can hit an endpoint via AJAX. This could be an ASP.NET MVC Controller or an .ashx handler.

Alternatively you can look at implementing something like SignalR, which via its Hubs, allows you to do magical things from javascript (and from the server, push notifications and things of that sort.)

You can't. C# is executed in the server side while javascript is execute in client side (browser).

Yes one can call C# Method from javascript using ajax in asp.net webforms also can do that in asp.net MVC

for example here is web forms example

    <script type="text/javascript">
    $(document).ready(function () {

     $.ajax({
         type: "POST",
         url: "Default.aspx/GetData",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (response) {
             alert(response.d);
         },
         failure: function (response) {
             alert(response.d);
         }
     });
 });
</script>

and new code behind c# method

[WebMethod]
public static string GetData()
{
    return "This string is from Code behind";
}

Output looks like this 在此输入图像描述 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM