Ajax call MVC Controller returns "NOT FOUND"

I am trying to invoke an MVC Controller action with AJAX passing some parameters.
I did this sometimes in this application and it works great.
I have no idea why only THIS ONE is not working.

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); } }); } 

This is my controller method:

 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); } 

Just a reminder that I am doing exactly what I did in other Ajax calls, but only that one in particular does not work.
Anyone have any ideas?

+2
jquery ajax asp.net-mvc
Dec 17 '15 at 19:38
source share
1 answer

Always use the Url.Action or Url.RouteUrl html helper methods to create a URL for action methods. It will take care of the proper construction of the URL regardless of the current page / path.

Assuming your js code is in razor mode, you can directly use the Url.Actio n method and assign it to the js variable.

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

It should work if you have a mode of action like this.

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

If your javascript is inside a separate javascript file, you can create the URL in your shaving view using the above helper methods and save this in a variable accessible to your external js file. Always avoid using the javascript namespace in this case to avoid possible problems with javascript global variables .

 @section Scripts { <script> var myApp = myApp || {}; myApp.Urls = myApp.Urls || {}; myApp.Urls.baseUrl = '@Url.Content("~")'; myApp.Urls.gravaCookieUrl = '@Url.Action("gravaCookie","entidades")'; </script> <script src="~/Scripts/PageSpecificExternalJsFile.js"></script> } 

And in your PageSpecificExternalJsFile.js file you can read it as

 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 

EDIT

If you just care about the root / base url of the site, you can simply use / as the first character of your URL.

 var urlToGrava2= "/entidades/gravaCookie"; 
+7
Dec 17 '15 at 19:42
source share



All Articles