0

我將全球化添加到C#MVC 5 Web應用程序。在大多數視圖中使用 我使用資源,它工作得很好。對於有很多定製的觀點,我想分開意見,每個意見不同的語言。 我跟着Brian Reiter post。我在視圖下添加了Globalization forlder,ISO 639-1雙字母宏語言代碼以及特定語言的主文件夾和索引視圖。根據客戶端區域重定向到獨特視圖

我知道我需要修改mechnisem來呈現視圖來考慮客戶端的語言環境。在Brian的帖子中,它是在Web表單上演示的,在我的解決方案中,我似乎沒有與他的示例中相同的WebFormViewEngine。

我會appriciate如果你可以指示我應該如何擴展mvc視圖引擎,以便正確的視圖將根據語言環境呈現。

謝謝。

+0

博客中的示例與MVC相關,而不是Web表單。但我想你使用Razor,所以你可以使用與例子中相同的代碼來擴展你的RazorViewEngine。 – Egor4eg

+0

謝謝@ Egor4eg你是對的。 – Shlo

回答

0

這我如何固定我的項目:

  1. 增加了一個類,將同時能延長該RazorViewEngine(繼承自它)。

我使用(以RazorViewEngine從WebFormsViewEngine,我的應用程序的文化餅乾和兩個字母languge從文化中提取)的微小變化在布賴恩·瑞特後的代碼(以上鍊接):

使用系統; using System.Collections.Generic;使用System.Linq的 ; using System.Web; using System.Web.Mvc; using System.Text.RegularExpressions;使用System.IO的 ; 使用LeadsWize.Helpers;使用System.Globalization的 ;

命名空間System.Web.Mvc { 公共類GlobalizationViewEngine:RazorViewEngine { 保護覆蓋IVIEW CreatePartialView(ControllerContext controllerContext,串partialPath) { partialPath = GlobalizeViewPath(controllerContext,partialPath); 返回新的RazorView(controllerContext,partialPath,null,false,FileExtensions,ViewPageActivator); }

protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) 
    { 
     viewPath = GlobalizeViewPath(controllerContext, viewPath); 
     return base.CreateView(controllerContext, viewPath, masterPath); 
    } 

    private static string GlobalizeViewPath(ControllerContext controllerContext, string viewPath) 
    { 
     var request = controllerContext.HttpContext.Request; 
     string cultureName = null; 
     HttpCookie cultureCookie = request.Cookies["_culture"]; 
     if (cultureCookie != null) 
      cultureName = cultureCookie.Value; 
     else 
      cultureName = request.UserLanguages != null && request.UserLanguages.Length > 0 ? 
        request.UserLanguages[0] : // obtain it from HTTP header AcceptLanguages 
        null; 
     // Validate culture name 
     cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe 
     var lang = (CultureInfo.CreateSpecificCulture(cultureName)).TwoLetterISOLanguageName; // this is to extract the two languge letters from the culture 
     if (lang != null && 
      !string.IsNullOrEmpty(lang) && 
      !string.Equals(lang, "en", StringComparison.InvariantCultureIgnoreCase)) 
     { 
      string localizedViewPath = Regex.Replace(
       viewPath, 
       "^~/Views/", 
       string.Format("~/Views/Globalization/{0}/", 
       lang 
       )); 
      if (File.Exists(request.MapPath(localizedViewPath))) 
      { viewPath = localizedViewPath; } 
     } 
     return viewPath; 
    } 
} 

}

  1. 添加有兩行Application_Stat在Global.asxs.cs

    ViewEngines.Engines.Clear(); 
        ViewEngines.Engines.Add(new GlobalizationViewEngine()); //this is our customized extended view engine to support the globaliztion in view folder Globalization. 
    

**請注意,文件夾arangemnet爲全球化視圖文件與Brian的文章完全相同。