David
David

Reputation: 16130

asp.net mvc - How to configure default parameters in routing

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

Answers (2)

Tommy
Tommy

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.

  • /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

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

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

Related Questions