Ajax调用MVC Controller返回“NOT FOUND”

我正在尝试使用AJAX调用MVC Controller动作传递一些参数。
我有时在这个应用程序中这样做,它工作正常。
我不知道为什么只有这一个不起作用。

function excluirDetalhe(button, tab) { var index = $(button).closest('tr').index(); var myTable = document.getElementById(tab); var id = myTable.rows[index].cells[0].innerHTML.trim(); $('#' + tab + ' tr:eq(' + index + ')').remove(); $.ajax({ traditional: true, url: "entidades/gravaCookie", type: 'post', data: { id: id, detalhe: "E" }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); } 

这是我的控制器方法:

 public void gravaCookie(string id, string detalhe) { string key = "een_id"; if (detalhe.Equals("E")) key = "een_id"; if (detalhe.Equals("C")) key = "eco_id"; if (detalhe.Equals("B")) key = "eba_id"; cookie.Values.Add(key, id); } 

只是提醒我,我正在完成其他Ajax调用中的操作,但只有这一个特别是无效。
有谁有想法吗?

始终使用Url.ActionUrl.RouteUrl html帮助程序方法来构建操作方法的URL。 无论您当前的页面/路径如何,它都会正确构建url。

假设您的js代码在剃刀视图中,您可以直接使用Url.Actio n方法并将其分配给您的js变量。

 url: "@Url.Action("gravaCookie","entidades")", 

应该假设你有这样的动作方法

 [HttpPost] public ActionResult gravaCookie(string id,string detalhe) { // to do : Return something } 

如果你的javascript在一个单独的javascript文件中,你可以使用上面的帮助器方法在你的剃刀视图中构建url,并将它保存在外部js文件代码可以访问的变量中。 这样做时务必使用javascript命名空间以避免全局javascript变量可能出现的问题

 @section Scripts {   } 

在你的PageSpecificExternalJsFile.js文件中,你可以像读取它一样

 var urlToGrava= myApp.Urls.gravaCookieUrl // Or With the base url, you may safely add the remaining url route. var urlToGrava2= myApp.Urls.baseUrl+"entidades/gravaCookie"; // Use urlToGrava now 

编辑

如果您只关心网站的根/基本url,您可以简单地使用/作为url的第一个字符。

 var urlToGrava2= "/entidades/gravaCookie";