在您的路线中,您可以使用以下内容:
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