【发布时间】:2017-09-06 22:17:50
【问题描述】:
我现在查看了几个线程,他们希望在 ASP 项目中从 JavaScript 调用 C# 方法。我无法弄清楚我做错了什么。这是我的 C# 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
namespace Selfservice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public String GetCredentials()
{
return User.Identity.Name.ToString();
}
}
}
这是我试图调用的 JavaScript:
window.onload = function () {
LiveSearch();
getCredentials();
//FetchAllUsers();
};
function getCredentials() {
$.ajax({
type: 'POST',
url: '@Url.Action("GetCredentials", "Home")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf8',
data: JSON.stringify(""),
success: function (cred) {
alert(cred);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
我不断收到 404 Not Found 状态。这是一个部署在 IIS 上的 ASP 站点,位于我的一个工作场所服务器上。我们正在使用 Windows 身份验证,因此我想获取登录者的凭据并将其存储起来以供以后使用。
我有点不知所措了。有人有什么想法吗?
【问题讨论】:
-
简单,你已经在你的action方法上声明了
[HttpGet],而你在jQuery中POST... -
@kayess 我不是 JS 奇才,但我看过的一些答案说这就是问题的答案。切换到“获取”并不能解决此问题。
-
您尝试将“/Home/GetCredentials”作为 url 吗?也像提到的更改 GET 删除 contentType 并将 dataType 更改为“text”,因为您的控制器没有返回 json
-
@kayess 评论是解决方案。只需将
[HttpGet]更改为[HttpPost]。 -
@Kris 这似乎至少可以解决获取请求。多谢,伙计。让它成为一个答案,我会接受它:)
标签: javascript c# asp.net ajax