2013-05-15 90 views
2

我想知道實現此目的的最佳方法是什麼。Mvc:具有不同名稱的相同ActionResult取決於url

我在我的控制器中的ActionResult,實際上卻news的名字,現在我需要internationlize我的網站,我不能有相同的news名字,它必須根據在那裏的訪問了該國改變。

例如,現在我需要類似的東西。

www.something.com/en/us/news英文版本

www.something.com/co/es/noticias西班牙語版本

你的下一個國家的地步。

我不認爲我需要創建X方法根據X網址,使完全一樣的,但我不知道如何實現它的一個非常有效的方式...感謝

回答

0

你的路由現在如何工作?如果你還沒有使用它,可能會像answer那樣工作。也許這是一個變化,以不同順序的URL部分,以滿足您的需求。例如,控制器不一定必須首先進入路徑(或者根本就不必使用相同的控制器名稱)。製作某種地圖,使用語言代碼作爲關鍵字,爲每個不同語言提供「新聞」一詞。

// populate this map somewhere - language code to word for "news" (and any other name of the controllers that you have) 
var newsControllerMap = new Dictionary<string, string>(); 
newsControllerMap["en"] = "news"; // etc. 

// ... 

// inside of the RouteConfig class (MVC 4) or RegisterRoutes() method in Global.asax.cs (MVC 3) 
// just making an assumption that whatever class/entity you use ("LanguageAndCountry" in this case) also has a country code to make this easier. Obviously this would be refactored to have better naming/functionality to make sense and meet your needs. 
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
    LanguageAndCountryRepository langRepo = new LanguageAndCountryRepository(); 
    var languagesandCountries = langRepo.GetAllLanguagesWithCountries(); 

    foreach (LanguageAndCountry langAndCountry in languagesandCountries) 
    { 
     routes.MapRoute(
     "LocalizationNews_" + langAndCountry.LanguageAbbreviation, 
     langAndCountry.LanguageAbbreviation + "/" + langAndCountry.CountryCode + "/" + newsControllerMap[langAndCountry.LanguageAbbreviation], 
     new { lang = language.LanguageAbbreviation, country = langAndCountry.CountryCode, controller = "News", action = "Index"}); 

     // map more routes to each controller you have, each controller having a corresponding map to the name of the controller in any given language 
    }