【问题标题】:need help to config mvc routing需要帮助来配置 mvc 路由
【发布时间】:2014-01-20 19:02:12
【问题描述】:

我有一个用户日志表,并希望通过userId 和日期时间参数提取记录。 如何创建路由配置,以便我的 url 可以是:

日志/用户 ID/

日志/用户 ID/年份/

日志/用户 ID/年/月/

日志/用户ID/年/月/日/

我的操作方法是这样的:

[HttpGet]
public ActionResult Read(int? userId, int? year, int? month, int? day)
{

}

当然我不想要一个路线,如果他们是一个有一些路线的解决方案,我很欣赏它,但我希望我的操作方法的语法可以像上面那样如果可能的话。 谢谢。

【问题讨论】:

  • 如果提供了用户 ID 和月份,但没有提供年或日,会发生什么?那么你的 URL 是什么样的呢?
  • 如果提供月份,用户ID和年份不能省略。如果提供了 day,则必须提供所有其他参数。这是一个搜索视图。我希望它灵活。
  • 这样做有什么问题:routes.MapRoute( name: "Logs", url: "logs/{user}/{year}/{month}/{day}", defaults: new {控制器=“日志”,操作=“详细信息”,用户=UrlParameter.Optional,年=UrlParameter.Optional,月=UrlParameter.Optional,日=UrlParameter.Optional});
  • @ganders 试试看,它不会工作。只有路由中的最后一个参数可以是可选的。您评论中的路线是有效的,但它不能使年份和月份为空ints,只有一天。
  • @danludwig 谢谢。

标签: asp.net-mvc asp.net-mvc-routing


【解决方案1】:

只有路由中的最后一个参数可以是可选的。我建议你这样做:

Logs/{userid}

... 其余参数使用查询字符串。

Logs/{userid}?year=2014&month=1&day=20

或者,您可以将整个日期作为可选字符串传递,然后在操作中对其进行解析:

Logs/{userId}/{date?}
Logs/{userId}/2014
Logs/{userId}/2014-01
Logs/{userId}/2014-01-20

[HttpGet]
public ActionResult Read(int userId, string date = null)
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多