2013-04-20 35 views

回答

0

您可以使用AJAX和JSON ActionResult以更優雅的方式實現這一點。

<button /> 
<label for="gender"></label> 

<script type="text/javascript"> 
    $("button").click(function() { 
     $('label[for=gender]').load('@Url.Action("ResourceLabel", new { labelKey = "Gender" })'); 
    }); 
</script> 

和服務器端,大大簡化了,但你的想法:

public ContentResult ResourceLabel(string labelKey) { 
    return Content(ResourceClass.GetString(labelKey)); 
} 
+2

不會爲每個標籤創建單獨的服務器請求嗎? – 2014-12-30 19:28:42

+0

它會;有多個標籤頁面上有更好的答案。我將把它留在這裏作爲單個標籤概念的證明。 – 2014-12-30 23:30:27

2

我會做類似如下:

<script type="text/javascript"> 
    var resourceStrings = { 
     @foreach (var resource in ViewBag.Resources) 
     { 
      { '@resource.Key' : '@resource.Value' }, 
     } 
    }; 
</script> 

這假定您已經創建了一個資源鍵/值的字典,並設置視圖袋屬性與字典。然後,您可以將這些資源作爲javascript對象查找來訪問。

$('label[name=gender]').html(resourceStrings['gender']); 

你可能詞典的詞典,如果你想通過文化訪問鍵:

$('label[name=gender]').html(resourceStrings['en_US']['gender']); 
7

我用的解決方案是使用剃刀來創建一個包含所有的JSON對象給定應用領域的資源字符串,如「客戶」。像這樣:

<script type="text/jscript"> 

@{ 

    ResourceSet resourceSet = JsCustomersRes.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); 
    var sbInitial = " var CustomersResourceObj = {"; 
    var sb = new StringBuilder(sbInitial); 
    var resEnum = resourceSet.GetEnumerator(); 
    while (resEnum.MoveNext()) 
    { 
     if (sb.ToString() != sbInitial) 
     { 
      sb.Append(","); 
     } 
     sb.Append("\"" + resEnum.Key + "\":\"" + resEnum.Value.ToString().Replace("\r\n", "").Replace("\"", "\\\"") + "\""); 
    } 
    sb.Append("}"); 
} 

@(Html.Raw(sb.ToString())); 

資源文件「JsCustomersRes」可以與沿着被放置在特定控制器觀看目錄或共享視圖目錄。 它應該在文件高級屬性中將「Custom Tool」設置爲「PublicResXFileCodeGenerator」。

然後,您可以得到JSON對象的資源字符串在你的腳本:

var resString = CustomersResourceObj[key]; 

,其中「關鍵」是你想要的資源串的密鑰字符串。 只需將Razor作爲局部視圖添加到您的佈局頁面或單個頁面中即可,就這樣!

+0

這是獲取資源的好方法。我的建議是,您應該只在腳本中使用密鑰(以'腳本'開頭的密鑰),以便您不會加載資源文件中的所有密鑰(假設您擁有超過1000個密鑰的資源文件) 。如果(!resEnum.Key.StartsWith('script')) 繼續;如果( )在你將有類似的東西: if(!resEnum.Key.StartsWith('script')) continue; – 2014-04-11 10:20:56

+0

好主意!感謝:) – davaus 2015-08-10 23:44:48

3

我的解決方案是基於這個http://codethug.com/2013/08/02/using-net-resources-in-javascript/和報價蒂姆·拉爾森的(作者)的話:

我們沒有做太多來確定使用什麼文化。瀏覽器在碰到服務器時,包含顯示 支持的文化的標題信息。 ASP.Net自動將此信息 納入CultureInfo.CurrentUICulture。我們將其傳遞給 GetResourceSet方法,該方法然後返回 與當前瀏覽器設置匹配的資源集。

因此,如果瀏覽器設置爲法語,法語資源,並且只有法語資源 將被返回。

陡峭1.創建一個資源文件RLocalizedText.resx到App_GlobalResources文件夾中。並創建填充所有的字符串。

陡峭2.創建ResourcesController

using System.Web.Mvc; 

namespace PortalACA.Controllers 
{ 
    public class ResourcesController : Controller 
    { 
     // GET: Resources 
     public ActionResult Index() 
     { 
      Response.ContentType = "text/javascript"; 
      return View(); 
     } 
    } 
}

陡峭3.創建一個從ResourcesController

@using System.Collections 
@using System.Globalization 
@using System.Resources 
@using Resources 
@{ 
    Layout = null; 
    // Get a set of resources appropriate to 
    // the culture defined by the browser 
    ResourceSet resourceSet = 
     @RLocalizedText.ResourceManager.GetResourceSet 
     (CultureInfo.CurrentUICulture, true, true); 
} 

// Define the empty object in javascript 
var Resources = {}; 
@foreach (DictionaryEntry res in resourceSet) 
{ 
    // Create a property on the javascript object for each text resource 
    @:[email protected] = "@Html.Raw(
     HttpUtility.JavaScriptStringEncode(res.Value.ToString()))"; 
}

Index.cshtml視圖您要使用它的選擇。

陡峭的4A(佈局)。如果你想使用它的整個網站,然後需要穿上_layout(共享視圖)這個腳本參考了@RenderSection

<script src="@Url.Content("~/Resources/Index")"></script> 
@RenderSection("scripts", required: false) 

陡峭4B(查看)。如果您只想在某些視圖中看到。

@section Scripts 
{ 
    <script src="@Url.Content("~/Resources/Index")"></script> 
} 

陡峭5.現在是時候使用它了。選擇一個您需要查看資源文件中的字符串的視圖並放置此代碼。

@section Scripts 
{ 
    <script> 
    $(document).ready(function() { 
     alert(Resources.General_Excepcion); 
    }); 
    </script> 
} 

這就是所有的人!希望它能幫助別人!

+0

智能感知不起作用在這種方法。 – Natiq 2017-08-18 11:46:29

1

我更喜歡創建一個包含所有資源作爲屬性的JavaScript對象。另外我避免創建一個局部視圖。相反,我將所需的語言作爲參數傳遞給腳本。這樣,您可以將腳本添加到全局模板中,而不是將其添加到每個頁面中。

基本上我有以下靜態方法的輔助靜態類:

public static JavaScriptResult JavascriptResources(ResourceManager manager, string resourceObjectName, CultureInfo culture) 
    { 
     ResourceSet resourceSet = manager.GetResourceSet(culture, true, true); 

     StringBuilder sb = new StringBuilder(); 

     sb.AppendFormat("var {0}=new Object();", resourceObjectName); 

     var enumerator = resourceSet.GetEnumerator(); 
     while (enumerator.MoveNext()) 
     { 
      sb.AppendFormat("{0}.{1}='{2}';", resourceObjectName, enumerator.Key, 
       System.Web.HttpUtility.JavaScriptStringEncode(enumerator.Value.ToString())); 
     } 

     return new JavaScriptResult() 
     { 
      Script = sb.ToString() 
     }; 
    } 

在我已經添加了以下控制器中的項目:

public class ResourcesController : Controller 
{ 
    [OutputCache(Duration = 36000, VaryByParam = "lang")] 
    // Duration can be many hours as embedded resources cannot change without recompiling. 
    // For the clients, I think 10 hours is good. 
    public JavaScriptResult Index(string lang) 
    { 
     var culture = new CultureInfo(lang); 
     return Helpers.JavascriptResources(Resources.Client.ResourceManager, 
      "Client", culture); 
    } 
} 

注意,我添加了一個參數給定全球JavaScript對象任何你想要的名字。在上面的例子中,我可以訪問翻譯像這樣的JS:

alert(Client.Info_Message); 

我們稱這個劇本,我註冊它在默認模板(例如在~/Shared/_layout.cshtml

<script type="text/javascript" src="~/resources/[email protected](ViewBag.Language)"></script> 

最好這種方式的工作方式是創建一個動作過濾器,以便在ViewData中自動輸入語言。這可能就像這樣:

public class LanguageInViewBagAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var controller = filterContext.Controller; 
     if (controller != null) 
      controller.ViewBag.Language = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; 
    } 
} 

然後,您可以裝飾控制器或動作與它在適用情況下,例如:

[LanguageInViewBag] 
public class HomeController : Controller 

或登記爲/App_start/Filters.cs

注意全局篩選器:我的實施假定您根據用戶的文化設置每個請求Thread.CurrentThread.CurrentCulture。這樣actionfilter就知道當前選擇的語言。

相關問題