I am working on an application surrounding sporting events. There are different types of events like a soccer tournament and a tennis tournament. Based on the type of tournament I want to have the requests proccessed by a different area. But the events and their tournament type is something that is configurable by users of the application and stored in the database.
Currrently I have this proof of concept:
public class SoccerTournamentAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "SoccerTournament";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
var soccerTournaments = new string[] { "championsleague", "worldcup" };
foreach (var tournament in soccerTournaments)
{
context.MapRoute(
string.Format("SoccerTournament_default{0}", tournament),
string.Format("{0}/{{controller}}/{{action}}/{{id}}", tournament),
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "Mvc3AreaTest1.Areas.SoccerTournament.Controllers" }
);
}
}
}
and it works only I want soccerTournaments to come from the database (not a problem) but I also want it to work ask soon as a new event/tournament type record is added to the database and that doesn't work in this case.
How can I make the area selection dynamic instead of hard coded into routes?
1 Answer 1
Area registration only occurs at the application start, so any tournaments added after startup will not be captured until a re-start.
To have a dynamic routing scheme for your tournaments, you must redefine your area route and add a RouteConstraint.
Redefine your route as follows:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"SoccerTournament_default",
"{tournament}/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { tournament = new MustBeTournamentName() },
new string[] { "Mvc3AreaTest1.Areas.SoccerTournament.Controllers" }
);
}
Than, you can create the MustBeTournamentName RouteConstraint to be similar to the RouteConstraint in the answer to this question: Asp.Net Custom Routing and custom routing and add category before controller