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