【问题标题】:asp.net Razor v3 jquery ajax post returns 404 not foundasp.net Razor v3 jquery ajax post返回404未找到
【发布时间】:2018-05-24 23:47:36
【问题描述】:

我最近启动了一个 Asp.net Razor v3 项目。这是我第一次使用这个(在我只使用 MVC 和 Web Forms 之前)

我正在努力获取由 jquery ajax 函数调用的代码来工作。在 Chrome 上调试时,我看到脚本返回 POST 404 (Not Found)

$.ajax({
  type: "POST",
  url: "../App_Code/GlobalSitesController/GetSiteTable",
  data: "{'siteName': 'Some Site' , 'daysDiff': '0'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
  document.getElementById("siteTable").innerHTML = response.responseText;
  },
  failure: function (response) {
  document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
  },
  error: function (response) {
  document.getElementById("siteTable").innerHTML = "ERROR" + response.responseText;
  }
});

public class GlobalSitesController : Controller
{
 [HttpPost]
 public string GetSiteTable(string siteName, int daysDiff)
 {
  return "some string";
 }
}

首先我注意到我的项目不包含 System.Web.Mvc,所以我通过 Nugget 添加了 Microsoft.AspNet.Mvc

完整的 Chrome 错误是 jquery-1.10.2.min.js:23 POST http://localhost:9997/App_Code/GlobalSitesController/GetSiteTable 404 (Not Found)。这是正确的 URL,应该可以正常工作

【问题讨论】:

    标签: jquery asp.net ajax razor


    【解决方案1】:

    原来url位需要如下形式

    url: '@url.Action("GetSiteTable", "GlobalSitesController")',
    

    (url需要如下初始化)

    System.Web.Mvc.UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
    

    【讨论】:

    • 不,它必须是url: '@Url.Action("GetSiteTable", "GlobalSites")', - 没有"Controller" 后缀,你不需要第二个代码sn-p - 它只是大写@Url.Action(...)
    • 你是对的。最后我发现我错过了_AppStart中的路由
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多