My ajax calls the wrong method in .net mvc 4 and I can’t figure out why.
My ajax:
function addItem(id, ammount) {
$.ajax({
url: "/Shoppingcart/AddItem?id="+id+"&ammount="+ammount,
type: "post",
cache: false,
success: function (result) {
alert("SUCCESS!!!");
},
error: function (textStatus, errorThrown) {
window.console.log(textStatus, errorThrown);
}
});
}
My mvc controller:
public class ShoppingcartController : Controller
{
//
// GET: /Shoppingcart/
public ActionResult Index()
{
// Method 1
}
[HttpPost]
public ActionResult AddItem(int id = -1, int ammount = 0)
{
return Redirect("~/Home");
}
}
My first method is getting called by the ajax, which is strange since I call /Shoppingcart/AddItem
Why is this happening and what should I do to make it work?
Solution:
The problem was not in the method calling but in the route stack. Apperantly the order in wich the routes are defined influences their importancy. The most specific route should always be the first route to be declared.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Index",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { id = @"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ControllerOnly",
url: "{controller}",
defaults: new { controller = "Home", action = "Index", id = 0 }
);
}
The problem is with your routing because the configured routes are matched in order.
So first you should put the more specify ones and at the end the more generic ones.
You have to most generic route with
url: "{controller}"first which matches the urllocalhost:1862/Shoppingcart/AddItem?id=18&ammount=1and uses theaction = "Index"instead of the actionAddItem.To fix it change your route order to:
To make urls like
/Product/18route correctly you need to change your"Index"route with using a constraint onidinstead ofUrlParameter.Optionaland you need to put it before the"Default"route: