I have a controller called Diary with an action called View.
If I receive a URL in the form "Diary/2012/6" I want it to call the View action with year = 2012 and month = 6.
If I receive a URL in the form "Diary" I want it to call the View action with year = [current year] and month = [current month number].
How would I configure the routing?
2 Answers 2
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
6 Comments
routes.MapRoute(
"DiaryRoute",
"Diary/{year}/{month}",
new { controller = "Diary", action = "View", year = UrlParameter.Optional, month = UrlParameter.Optional }
);
and the controller action:
public ActionResult View(int? year, int? month)
{
...
}
3 Comments
int? instead of int? Did you do the same thing?