Ajax调用错误的方法

时间:2012-10-22 14:01:44

标签: .net ajax asp.net-mvc-4

我的ajax在.net mvc 4中调用了错误的方法,我无法弄清楚原因。

我的阿贾克斯:

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

我的mvc控制器:

public class ShoppingcartController : Controller
{
    //
    // GET: /Shoppingcart/

    public ActionResult Index()
    {
        // Method 1
    }

    [HttpPost]
    public ActionResult AddItem(int id = -1, int ammount = 0)
    {
        return Redirect("~/Home");
    }
}

我的第一种方法是被ajax调用,这很奇怪,因为我调用了/ Shoppingcart / AddItem 为什么会发生这种情况,我该怎么做才能使它发挥作用?

解决方案: 问题不在于调用方法,而是在路由堆栈中。显然,定义路线的顺序会影响它们的重要性。最具体的路线应始终是要申报的第一条路线。

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

1 个答案:

答案 0 :(得分:3)

问题在于您的路由,因为配置的路由按顺序匹配。

首先,你应该把更多指定的那些,最后是更通用的那些。

您必须首先使用url: "{controller}"的最常用路由与网址localhost:1862/Shoppingcart/AddItem?id=18&ammount=1匹配,并使用action = "Index"代替操作AddItem

要修复它,请将路线订单更改为:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Index",
    url: "{controller}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "ControllerOnly",
    url: "{controller}",
    defaults: new { controller = "Home", action = "Index", id = 0 }
);

要正确设置/Product/18路由的网址,您需要使用"Index"上的约束而不是id来更改UrlParameter.Optional路由,并且需要放置它在"Default"路线之前:

routes.MapRoute(
    name: "Index",
    url: "{controller}/{id}",
    defaults: new { controller = "Home", action = "Index" },
    constraints: new {id = @"\d+"}
);