2011-11-16 60 views
0

我正在研究圍繞體育賽事的應用程序。有足球比賽和網球比賽等不同類型的賽事。根據比賽的類型,我希望由另一個區域處理請求。但事件及其比賽類型可由應用程序的用戶配置並存儲在數據庫中。基於路線參數值的asp.net mvc動態區域選擇

Currrently我有概念的證明了這一點:

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" } 
       ); 
     } 
    } 
} 

,我想soccerTournaments來自數據庫(不是問題),它僅適用,但我也希望它的工作很快問作爲一個新的事件/比賽類型記錄被添加到數據庫中,並且在這種情況下不起作用。

如何使區域選擇動態而不是硬編碼到路線中?

回答

1

區域註冊只發生在應用程序啓動時,所以啓動後添加的任何錦標賽都不會被捕獲,直到重新啓動。

要爲您的錦標賽提供動態路線方案,您必須重新定義您的地區路線並添加RouteConstraint

重新定義您的路線如下:

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" } 
    ); 
} 

比,你可以創建MustBeTournamentName RouteConstraint是在回答這個問題類似於RouteConstraint:Asp.Net Custom Routing and custom routing and add category before controller