【问题标题】:asp.net mvc - How to configure default parameters in routingasp.net mvc - 如何在路由中配置默认​​参数
【发布时间】:2012-06-18 19:56:14
【问题描述】:

我有一个名为 Diary 的控制器和一个名为 View 的操作。

如果我收到“Diary/2012/6”形式的 URL,我希望它调用 View 操作,year = 2012 和 month = 6。

如果我收到“日记”形式的 URL,我希望它使用 year = [当前年份] 和 month = [当前月份编号] 调用 View 操作。

如何配置路由?

【问题讨论】:

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


    【解决方案1】:

    在您的路线中,您可以使用以下内容:

    routes.MapRoute(
                    "Dairy", // Route name
                    "Dairy/{year}/{month}", // URL with parameters
                    new { controller = "Dairy", action = "Index", year = DateTime.Now.Year, month = DateTime.Now.Month });
    

    如果未提供年/月,将发送当前值。如果提供了它们,那么路由将使用这些值。

    • /Dairy/ -> 年 = 2012,月 = 6
    • /Dairy/1976/04 -> 年 = 1976 年,月 = 4

    编辑

    除了下面的注释之外,这是用于使用上述条件创建新项目的代码。

    Global.Asax

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            "Default", // Route name
            "Dairy/{year}/{month}", // URL with parameters
            new { controller = "Dairy", action = "Index", year = DateTime.Now.Year, month = DateTime.Now.Month } // Parameter defaults
        );
    
    }
    

    奶制品控制器

    public ActionResult Index(int year, int month)
    {
        ViewBag.Year = year;
        ViewBag.Month = month;
        return View();
    }
    

    观点

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    Month - @ViewBag.Month <br/>
    Year - @ViewBag.Year
    

    结果:

    • /Dairy/1976/05 -> 输出 1976 年和 5 月
    • / -> 年输出 2012,月输出 6

    【讨论】:

    • 如果我不提供 URL 中的参数,我会得到旧的“参数字典包含空条目”schtick。
    • @David - 你还有其他路线可能会与这条路线混淆吗?我刚刚使用上述方法创建了一个新项目,并且参数字典没有问题。
    • 哦,有趣。我将删除我的其他路线并检查。
    • @David - 您可能需要在路由中显式调用乳制品控制器,以便路由与您可能已定义的任何其他路由正确匹配。更新了上面的示例。
    • 我只需要重新安排路线!非常感谢您的帮助。
    【解决方案2】:
    routes.MapRoute(
        "DiaryRoute",
        "Diary/{year}/{month}",
        new { controller = "Diary", action = "View", year = UrlParameter.Optional, month = UrlParameter.Optional }
    );
    

    和控制器动作:

    public ActionResult View(int? year, int? month)
    {
        ...
    }
    

    【讨论】:

    • 如果我不提供 URL 中的参数,我会得到旧的“参数字典包含空条目”schtick。
    • 您是否注意到我在动作签名中将参数声明为可空整数 => int? 而不是 int?你也做过同样的事情吗?
    • 对不起,我的错,你是对的。我正在标记 Tommy 的答案,因为默认值的设置是在我更喜欢的路由中处理的。谢谢。
    猜你喜欢
    • 2012-09-12
    • 2017-10-08
    • 1970-01-01
    • 2011-08-01
    • 2010-11-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多