Reputation: 16130
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?
Upvotes: 3
Views: 2271
Reputation: 39817
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.
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:
Upvotes: 2
Reputation: 1039438
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)
{
...
}
Upvotes: 2