尝试更改我的 MVC 5 应用程序中的路由
Trying to change the routing in my MVC 5 application
当我开始创建这个网站时,我并没有想太多,忘记了将产品类别添加到我的数据模型中。现在,当我单击“产品”时,它会显示显示所有项链的“索引”视图。有这样的路径 /Products/Index。
现在我要做的是更改路由,以便索引显示类别列表,然后当您单击时,比如项链,我想要一个像这样的路径 /Products/Necklaces/Index,所有类别依此类推.我可以在我的 Products 文件夹(我的视图所在的位置)中添加文件夹吗,或者我如何更改路由以适应此更改?
我在 RouteConfig.cs 文件中试过这个
routes.MapRoute(
name: "Products",
url: "{controller}/{category}/{action}/{id}",
defaults: new { controller = "Products", category = "Necklaces", action = "Index", id = UrlParameter.Optional }
);
但是/Products/Necklaces/Index仍然给我一个404错误
这里有两种方法可以解决这个问题。
您可以像以前一样将以下内容添加到您的 RouteConfig.cs。
routes.MapRoute(
name: "Products",
url: "{controller}/{category}/{action}/{id}",
defaults: new { controller = "Products", action = "Index", id = UrlParameter.Optional }
);
或
将此添加到您的 RouteConfig.cs。
routes.MapMvcAttributeRoutes();
然后将此路由属性添加到您的索引操作中。
// The id? means it is an optional parameter.
[Route("Products/{category}/Index/{id?}")]
public ActionResult Index(string category, string id)
{
return View();
}
这两个都可以。
确保您的 Action 对于这两种方法都符合要求。
当我开始创建这个网站时,我并没有想太多,忘记了将产品类别添加到我的数据模型中。现在,当我单击“产品”时,它会显示显示所有项链的“索引”视图。有这样的路径 /Products/Index。
现在我要做的是更改路由,以便索引显示类别列表,然后当您单击时,比如项链,我想要一个像这样的路径 /Products/Necklaces/Index,所有类别依此类推.我可以在我的 Products 文件夹(我的视图所在的位置)中添加文件夹吗,或者我如何更改路由以适应此更改?
我在 RouteConfig.cs 文件中试过这个
routes.MapRoute(
name: "Products",
url: "{controller}/{category}/{action}/{id}",
defaults: new { controller = "Products", category = "Necklaces", action = "Index", id = UrlParameter.Optional }
);
但是/Products/Necklaces/Index仍然给我一个404错误
这里有两种方法可以解决这个问题。
您可以像以前一样将以下内容添加到您的 RouteConfig.cs。
routes.MapRoute(
name: "Products",
url: "{controller}/{category}/{action}/{id}",
defaults: new { controller = "Products", action = "Index", id = UrlParameter.Optional }
);
或
将此添加到您的 RouteConfig.cs。
routes.MapMvcAttributeRoutes();
然后将此路由属性添加到您的索引操作中。
// The id? means it is an optional parameter.
[Route("Products/{category}/Index/{id?}")]
public ActionResult Index(string category, string id)
{
return View();
}
这两个都可以。
确保您的 Action 对于这两种方法都符合要求。