2012-06-18 130 views
3

我有一个名为Diary的控制器,其操作名为Viewasp.net mvc - 如何在路由中配置默认​​参数

如果我接收的URL的形式“日记/ 2012/6”我希望它调用View行动year = 2012和month = 6

如果我的形式接收的URL“日记“我希望它通过year = [当前年份]和month = [当前月份号码]调用View行动。

我该如何配置路由?

回答

2

在你的路线,你可以使用以下命令:

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

如果不能提供一年/月,当前值将被发送。如果提供它们,那么这些值将被该路线使用。

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

EDIT

除下面的评论外,这是用于使用上述标准创建新项目的代码。

的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 
    ); 

} 

DairyController

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 

结果:

  • /乳制品/ 1976年/ 05 - >输出1976年一年,5月
  • /- >输出2012年6月分
+0

如果我不提供URL中的参数,我会得到旧的'参数字典包含空条目'schtick。 – David

+0

@大卫 - 你有其他路线可能会与这一个?我刚刚使用上述方法创建了一个新项目,并且与参数字典没有任何问题。 – Tommy

+0

哦,有趣。我会删除我的其他路线并检查。 – 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) 
{ 
    ... 
} 
+0

如果我没有在URL中提供的参数,我得到旧的'参数字典包含空条目'schtick。 – David

+0

你有没有注意到我是如何在action signature =>'int?'而不是'int'中声明参数为可为空的整数?你做了同样的事情吗? –

+0

对不起,我不好,你说得对。我正在标记Tommy的答案,因为默认值的设置是在路由中处理的,我更喜欢。谢谢。 – David