如何从 JavaScript 调用 C# 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18441194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a C# function from JavaScript?
提问by IamNumber5
I want to call CsharpFunction
, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True
or False
, CsharpFunction
was called regardless!
我想CsharpFunction
从 JavaScript调用,代码隐藏中的 C# 函数。我尝试了下面的代码,但是无论 JavaScript 条件是True
还是False
,都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# 函数?
采纳答案by user3098137
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
}
回答by Bart Friederichs
You can't. Javascript runs client side, C# runs server side.
你不能。Javascript 运行客户端,C# 运行服务器端。
In fact, your server will run all the C# code, generatingJavascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.
事实上,您的服务器将运行所有 C# 代码,生成Javascript。然后,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 等技术,如其他答案中所述。
回答by Russell Young
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
如果您打算从客户端进行服务器调用,则应使用 Ajax - 查看类似 Jquery 的内容并使用 $.Ajax() 或 $.getJson() 调用服务器函数,具体取决于您返回的类型'是你想要执行的动作。
回答by Rohit
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
处理程序上您可以访问变量的值并调用服务器方法。
回答by Vijay Mungara
.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 函数中,当调用您的 CS 页面函数时.... 项目的名字,然后是 CS 页面的命名空间名称,然后是函数名称
回答by Stephen Kennedy
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 方法,允许客户端检索有关 1 个或所有产品的详细信息(在现实世界中,产品可能会从数据库加载):
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 easilycreate a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pagesand/or Swashbuckle.
这不仅允许您轻松创建现代 Web API,如果您需要变得非常专业并记录它,您还可以使用ASP.NET Web API 帮助页面和/或Swashbuckle。
Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. In that case you will need to add routing instructions into the Application_Start
method in the file Global.asax
:
Web API 可以改装(添加)到现有的 ASP.NET Web 窗体项目。在这种情况下,您需要将路由指令添加到Application_Start
文件中的方法中Global.asax
:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Documentation
文档
- Tutorial: Getting Started with ASP.NET Web API 2 (C#)
- Tutorial for those with legacy sites: Using Web API with ASP.NET Web Forms
- MSDN: ASP.NET Web API 2
- 教程:ASP.NET Web API 2 (C#) 入门
- 适用于旧网站的教程:将 Web API 与 ASP.NET Web 窗体一起使用
- MSDN:ASP.NET Web API 2
回答by Patrick Knott
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)
}