【发布时间】:2012-10-22 14:01:43
【问题描述】:
我的 ajax 在 .net mvc 4 中调用了错误的方法,我不知道为什么。
我的 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);
}
});
}
我的 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 }
);
}
【问题讨论】:
-
您的代码看起来不错,您确定调用了
addItem函数吗?请在 fiddler/dev-console/firebug 中检查您向服务器发送了哪些请求。 -
根据提琴手的说法,正在调用 url localhost:1862/Shoppingcart/AddItem?id=18&ammount=1。除了上面我的成功消息被正确触发
-
您是否有任何自定义路由,如果有,请发布您的路由配置?
-
根据 jQuery 文档,您应该使用“POST”而不是“post”,但我真的怀疑它会改变什么... :-) 也许您应该使用“data”而不是查询字符串也。
-
nemesv 我将 routeconfig 添加到帖子中。 jovnas 我尝试使用数据,没有效果。
标签: .net ajax asp.net-mvc-4