从 JavaScript 调用 C# 方法
Calling a C# method from JavaScript
我想在我的 JavaScript 工厂 LoginFactory.js
中从我的控制器 AccountController.cs
调用一个方法 GetAccount
。像这样:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
我试过使用 [WebMethod]
和 Ajax,但我无法正常工作:我收到 404 响应。
假设 您的 GetAccount
方法可以在您的应用程序运行时在 /Account/GetAccount
到达,您可以使用以下内容:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
注意 - 这取决于 jQuery。
这会导致 浏览器 向 /Account/GetAccount
发出请求,就像您在 URL 中输入 URL 一样栏,但当然,捕获返回的 json 用于您的客户端 (javascript) 脚本。
如果此 returns 是 404,则值得检查您的路由。
我想在我的 JavaScript 工厂 LoginFactory.js
中从我的控制器 AccountController.cs
调用一个方法 GetAccount
。像这样:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
我试过使用 [WebMethod]
和 Ajax,但我无法正常工作:我收到 404 响应。
假设 您的 GetAccount
方法可以在您的应用程序运行时在 /Account/GetAccount
到达,您可以使用以下内容:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
注意 - 这取决于 jQuery。
这会导致 浏览器 向 /Account/GetAccount
发出请求,就像您在 URL 中输入 URL 一样栏,但当然,捕获返回的 json 用于您的客户端 (javascript) 脚本。
如果此 returns 是 404,则值得检查您的路由。