This project is read-only.

Default route value that isn't a constant?

May 30, 2012 at 9:48 PM
Edited May 30, 2012 at 9:49 PM

As an example:

[CustomRoute("{year}")]
public ActionResult Index([FromRoute(Constraint = @"\d{4}")]int year){}

I'd like to do this in NewsController.cs:

[CustomRoute("{year}")]
public ActionResult Index([FromRoute(Constraint = @"\d{4}")]int year = DateTime.Now.Year){}

...which would be a converted version of this from Global.asax.cs:

routes.MapRoute(
	"News",
	"News/{year}",
	new { controller = "News", action = "Index", year = DateTime.Now.Year },
	new { year = @"\d{4}" },
	new[] { "..." }
);

But, where that's allowed in Global.asax.cs, the non-constant value for year is not valid as part of an Attribute.

In other words, an ActionLink for:

@Html.ActionLink(Resources.Global.Press_Room, "Index", "News")

...would ideally generate:

/News/2012

Any way around that?

May 30, 2012 at 10:15 PM

This should work:

var codeRoutes = routes.MapCodeRoutes(...);

codeRoutes.Single(r => r.Url == "News/{year}").Defaults["year"] = DateTime.Now.Year;

Marked as answer by maxtoroq on 10/15/2013 at 10:04 AM
May 30, 2012 at 10:29 PM

Brilliant!