asp.net Razor v3 jquery ajax post returns 404 not found

问题内容:

I recently started a Asp.net Razor v3 project. It’s the first time I use this (before I only used MVC and Web Forms)

I am struggling to get a code behind that gets called by a jquery ajax function to work. When debugging on Chrome I see that the script returns 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";
 }
}

First I noticed that my project didn’t include System.Web.Mvc so I added Microsoft.AspNet.Mvc via Nugget

The full Chrome error is jquery-1.10.2.min.js:23 POST http://localhost:9997/App_Code/GlobalSitesController/GetSiteTable 404 (Not Found). This is the correct URL and should be working

问题评论:

答案:

答案1:

It turns out the url bit needs to be in the following form

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

(url needs to be initialised as in below)

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

答案评论:

原文地址:

https://stackoverflow.com/questions/47753186/asp-net-razor-v3-jquery-ajax-post-returns-404-not-found

Add a Comment