使用默认路由:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{category}",
defaults: new { controller = "Home", action = "Index", category = UrlParameter.Optional }
);
正在生成的 URL 如下所示:www.domain.com/Home/Index/Category
但是,如果用户正在浏览特定类别,我希望 URL 看起来像这样:www.domain.com/Home/Category
如果没有选择类别:www.domain.com/Home
我添加了这段代码:
routes.MapRoute(null, "{controller}/{category}", new { action = "Index" });
routes.MapRoute(null, "{controller}/{action}", new { controller = "Home", action = "Index", category = (string)null });
并且 URL 开始看起来像我想要的那样,但是!在控制器中调用动作的表单方法不再起作用:
@using (Html.BeginForm("AddToCart", "Home"))
{
@Html.Hidden("category", Model.CurrentCategory)
@Html.Hidden("productId", p.ProductId)
<input type="submit" value="Add To Cart" />
}
由于某种原因,表单操作方法似乎调用了错误的路线,即:
routes.MapRoute(null, "{controller}/{category}", new { action = "Index" });
并不是
routes.MapRoute(null, "{controller}/{action}", new { controller = "Home", action = "Index", category = (string)null });
因为当单击提交按钮时,浏览器重定向到 url: www.domain.com/Home/AddToCart 并且永远不会调用“Home”控制器中的操作方法“AddToCart”。