【问题标题】:asp.net mvc multiple parameters to an action, routing problemasp.net mvc多个参数到一个动作,路由问题
【发布时间】:2010-12-03 13:16:34
【问题描述】:

我的问题是我为我的操作提供了 3 个参数(类别、城市、页面),其中一些可能为空,因为我需要进行 3 次过滤:

  • 按类别分类(category != null && city == null)
  • 一个城市(category == null && city != null)
  • 他们俩一个(category != null && city != null)

我的问题在于路由。 当(category != null && city == null) 它不起作用。它从我的操作空值中提供类别参数,我的城市参数接收类别的值。

我的 Global.asax:

routes.MapRoute(
            "ListByCity",
            "Advertisers/{city}/{page}",
            new { controller = "Advertisers", action = "List"  }
            );

        routes.MapRoute(
            "ListByCategory",
            "Advertisers/{category}/{page}",
            new { controller = "Advertisers", action = "List" }
            );

        routes.MapRoute(
            "List",
            "Advertisers/{category}/{city}/{page}",
            new { controller = "Advertisers", action = "List" }
            );

请帮帮我。

【问题讨论】:

  • 改用查询字符串

标签: c# asp.net-mvc


【解决方案1】:

以相反的方式思考问题。如果您有 URL http://YourServer/Advertisers/Text,您如何知道该文本是类别还是城市? 您可以使用正则表达式解决匹配问题,但城市和类别都是字符串,因此您无法告诉路由系统匹配哪个。 你必须区分它们。也许创建一个匹配 /Advertisers/Categories/{category} 和其他匹配 /Advertisers/Cities/{city} 的路由。

【讨论】:

  • 如果我从数据库中包含我的城市/类别,则可以使用正则表达式解决匹配问题。它可能会起作用。
【解决方案2】:

在我看来,这更像是三个独立的操作:

/Advertisers/List/{category}/{city}/{page}
/Advertisers/ListByCity/{city}/{page}
/Advertisers/ListByCategory/{category}/{page}

这些都可以调用控制器中的通用方法来为列表视图准备模型。

编辑:

或者您需要添加一个名为“all”的类别和一个名为“all”的城市,然后您只能离开一条路线:

/Advertisers/List/{category}/{city}/{page}

【讨论】:

  • 我同意你的观点,但我不需要在 url 上使用我的操作名称。
  • 为什么不呢?这是默认的做法:{controller}/{action}/{parameter}。此外,如果不使用查询字符串或在 URL 中包含搜索类型作为参数,我认为您想要做的事情是不可能的。或者更改参数的顺序(将 {page} 移到前面),然后在生成列表之前确定控制器中的参数类型。
【解决方案3】:

最好使用查询字符串。

请参考https://stackoverflow.com/questions/4....

它也有不少不错的建议。

【讨论】:

    【解决方案4】:

    我同意@MCL 的编辑。我认为您也可以采取这种方法而无需采取行动。

    /Advertisers/All/NewYork/1
    /Advertisers/SomeCategory/NewYork/2
    

    你设置你的路线是这样的:

    routes.MapRoute(
            "List",
            "Advertisers/{category}/{city}/{page}",
            new { controller = "Advertisers", action = "List" });
    

    你的 Action 看起来会是这样的:

    public ActionResult List ( string category, string city, int page ) { .. }
    

    在这种情况下,我也不同意查询字符串。当然,它更容易,但我觉得这种 URI 模式将成为您应用程序的核心部分,如果不为其设置适当的路由系统,从长远来看会阻碍您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2023-01-25
      • 2011-06-02
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多