【问题标题】:Multiple Parameters MVC routing多参数 MVC 路由
【发布时间】:2017-04-09 02:27:17
【问题描述】:

我正在制作一个类似图书馆的网站。在这个库中,一篇文章可以有一个类别,并且该类别最多可以有 2 个父类别,例如:“世界 > 国家 > 城市”。

我想将所有文章的所有视图显示都保留在一个名为 LibraryController 的控制器中。使用的 2 个操作是 Article(string id)Category(string[] ids)

要查看名为“圣殿骑士团”的文章,用户必须输入:/library/article/the-templar-order

好的,现在是类别。我脑子里有两种方法,这个例子是查看“城市”类别:

  1. 简单方法:/library/world-country-city
  2. 我想要的那个:/library/world/country/city
  3. 我不想要的,因为它太笨拙了:/library/category/world/country/city

但是对于如何创建一个需要 3 个参数且基本上没有操作的路由,我有点困惑。除了第一个参数“world”之外,其余的应该是可选的,像这样:"/library/world/" > "/library/world/country/" > "/library/world/country/city/"

那么我该如何创建这样的路线呢?

解决方案

RouteConfig.cs

// GET library/article/{string id}
routes.MapRoute(
    name: "Articles",
    url: "Library/Article/{id}",
    defaults: new { controller = "Library", action = "Article", id = "" }
    );

// GET library/
routes.MapRoute(
    name: "LibraryIndex",
    url: "Library/",
    defaults: new { controller = "Library", action = "Index" }
    );

// GET library/category/category/category etc.
routes.MapRoute(
    name: "Category",
    url: "Library/{*categories}",
    defaults: new { controller = "Library", action = "Category" }
    );

【问题讨论】:

    标签: c# asp.net-mvc-5 asp.net-mvc-routing


    【解决方案1】:

    您可以通过以下两条路线来实现。

    // GET library/article/the-templar-order
    routes.MapRoute(
         name: "Articles",
         url: "Library/Article/{id}",
         defaults: new { controller = "Library", action = "Article" }
     );
    
    // GET library/world/country/city
    routes.MapRoute(
         name: "Category",
         url: "Library/{*categories}",
         defaults: new { controller = "Library", action = "Category" }
     );
    

    并对目标动作稍作修改

    public ActionResult Category(string categories) {
        categories = categories ?? string.Empty;
        var ids = categories.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
        //...other code
    }
    

    【讨论】:

    • sry 我有点太快接受答案了。我在 /library/world/country/city 之外的任何地方都收到“找不到资源”。这意味着像 /library/world 这样的 url 会导致错误。
    • 显示您映射路线的顺序。顺序很重要,因为第一场比赛获胜。这可能意味着另一个路由在处理之前捕获了该 url。
    • 谢谢队友,用最终解决方案更新了问题......现在它完美运行......确实是导致问题的映射路线的顺序......
    • 没问题。乐意效劳。请记住,在更一般的路线之前需要映射特定的路线。编码快乐!!!
    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2011-01-15
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多