简体   繁体   English

如何从JavaScript调用C#函数?

[英]How to call a C# function from JavaScript?

I want to call CsharpFunction , a C# function in code-behind, from JavaScript. 我想从JavaScript调用CsharpFunction ,这是代码隐藏的C#函数。 I tried the code below but whether the JavaScript condition is True or False , CsharpFunction was called regardless! 我尝试了下面的代码,但是无论JavaScript条件是True还是FalseCsharpFunction调用CsharpFunction

JavaScript code: JavaScript代码:

if (Javascriptcondition > 0) {
   <%CsharpFunction();%>
}

C# code behind: 后面的C#代码:

protected void CsharpFunction()
{
  // Notification.show();
}

How do I call a C# function from JavaScript? 如何从JavaScript调用C#函数?

You can use a Web Method and Ajax: 您可以使用Web方法和Ajax:

<script type="text/javascript">             //Default.aspx
   function DeleteKartItems() {     
         $.ajax({
         type: "POST",
         url: 'Default.aspx/DeleteItem',
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $("#divResult").html("success");
         },
         error: function (e) {
             $("#divResult").html("Something Wrong.");
         }
     });
   }
</script>

[WebMethod]                                 //Default.aspx.cs
public static void DeleteItem()
{
    //Your Logic
}
.CS File    
    namespace Csharp
    {
      public void CsharpFunction()
      {
        //Code;
      }
    }

    JS code:
    function JSFunction() {
            <%#ProjectName.Csharp.CsharpFunction()%> ;
    }

Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name 注意:在JS Function中,当调用您的CS页面函数时。...项目的名称,然后是CS页面的名称空间的名称,然后是函数名称

A modern approach is to use ASP.NET Web API 2 (server-side) with jQuery Ajax (client-side). 现代方法是将ASP.NET Web API 2 (服务器端)与jQuery Ajax(客户端)一起使用。

Like page methods and ASMX web methods, Web API allows you to write C# code in ASP.NET which can be called from a browser or from anywhere, really! 像页面方法和ASMX Web方法一样,Web API允许您在ASP.NET中编写C#代码,这实际上可以从浏览器或任何地方调用!

Here is an example Web API controller, which exposes API methods allowing clients to retrieve details about 1 or all products (in the real world, products would likely be loaded from a database): 这是一个示例Web API控制器,它公开了API方法,这些方法允许客户端检索有关一种或所有产品的详细信息(在现实世界中,产品很可能是从数据库中加载的):

public class ProductsController : ApiController
{
    Product[] products = new Product[] 
    { 
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    };

    [Route("api/products")]
    [HttpGet]
    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    [Route("api/product/{id}")]
    [HttpGet]
    public IHttpActionResult GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

The controller uses this example model class: 控制器使用以下示例模型类:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

Example jQuery Ajax call to get and iterate over a list of products: 示例jQuery Ajax调用以获取并迭代产品列表:

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON("/api/products")
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
        });
});

Not only does this allow you to easily create a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pages and/or Swashbuckle . 这不仅使您可以轻松创建现代的Web API,而且还可以使用ASP.NET Web API帮助页面和/或Swashbuckle使其真正专业化并对其进行文档化。

Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. 可以将Web API改装(添加)到现有的ASP.NET Web Forms项目中。 In that case you will need to add routing instructions into the Application_Start method in the file Global.asax : 在这种情况下,您将需要在Global.asax文件的Application_Start方法中添加路由指令:

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
);

Documentation 文献资料

Server-side functions are on the server-side, client-side functions reside on the client. 服务器端功能位于服务器端,客户端功能位于客户端。 What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method. 您所要做的是必须设置隐藏的表单变量并提交表单,然后在页面上使用Page_Load处理程序可以访问变量的值并调用服务器方法。

More info can be found here and here 更多信息可以在这里这里找到

如果要从客户端进行服务器调用,则应使用Ajax-查看类似Jquery的东西,并使用$ .Ajax()或$ .getJson()来调用服务器函数,具体取决于您返回的是哪种类型您要执行的动作或动作。

Use Blazor http://learn-blazor.com/architecture/interop/ 使用Blazor http://learn-blazor.com/architecture/interop/

Here's the C#: 这是C#:

namespace BlazorDemo.Client
{
   public static class MyCSharpFunctions
   {
       public static void CsharpFunction()
       {
          // Notification.show();
       }
   }
}

Then the Javascript: 然后是Javascript:

const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
   Blazor.platform.callMethod(CsharpFunction, null)
}

You can't. 你不能 Javascript runs client side, C# runs server side. Javascript运行客户端,C#运行服务器端。

In fact, your server will run all the C# code, generating Javascript. 实际上,您的服务器将运行所有C#代码,并生成 Javascript。 The Javascript then, is run in the browser. 然后,JavaScript将在浏览器中运行。 As said in the comments, the compiler doesn't know Javascript. 如评论中所述,编译器不知道Javascript。

To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers. 要调用服务器上的功能,您必须使用AJAX之类的技术,如其他答案所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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