In your routes, you can use the following:
routes.MapRoute(
"Dairy", // Route name
"Dairy/{year}/{month}", // URL with parameters
new { controller = "Dairy", action = "Index", year = DateTime.Now.Year, month = DateTime.Now.Month });
If year/month are not provided, the current values will be sent. If they are provided, then those values will be used by the route.
- /Dairy/ -> year = 2012, month = 6
- /Dairy/1976/04 -> year =
1976, month = 4
EDIT
In addition to the comment below, this is the code used to create a new project using the above criteria.
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();
}
The View
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Month - @ViewBag.Month <br/>
Year - @ViewBag.Year
Results:
- /Dairy/1976/05 -> outputs 1976 for year and 5 for the month
- / -> outputs 2012 for year and 6 for month