在ASP.NET MVC中将资源字符串公开给JavaScript文件的最佳方法?

Pol*_*Pol 18 javascript asp.net asp.net-mvc localization

在Razor视图中使用资源字符串(.resx)很容易,但是如何在JavaScript文件中使用它?目前我手动将字符串从Razor视图传递到JavaScript构造函数参数中的脚本,但我想要一种更自动地执行此操作的方法,因此我不必传递我需要的每个资源字符串.

dav*_*aus 7

我使用的解决方案是使用Razor创建一个json对象,该对象包含给定应用程序区域的所有资源字符串,例如"Customers".像这样:

<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()));
Run Code Online (Sandbox Code Playgroud)

资源文件"JsCustomersRes"可以与特定的控制器视图目录一起放置,也可以放在共享视图目录中.它应该在文件高级属性中将"自定义工具"设置为"PublicResXFileCodeGenerator".

然后,您可以从脚本中的json对象获取资源字符串:

var resString = CustomersResourceObj[key];
Run Code Online (Sandbox Code Playgroud)

其中"key"是您想要的资源字符串的关键字符串.只需根据需要将Razor添加为布局页面或单个页面的部分视图即可!

  • 这是获取资源的好方法。我的建议是,您应该在仅在脚本中使用的资源中拥有键(键以“脚本”开头),这样您就不会从资源文件中加载所有键(假设您拥有超过 1000 个键的资源文件) . 所以在此期间你会得到类似的东西: if(!resEnum.Key.StartsWith('script')) continue; (2认同)

equ*_*man 7

我的解决方案基于此http://codethug.com/2013/08/02/using-net-resources-in-javascript/并引用 Tim Larson(作者)的话:

我们不必做太多事情来确定要使用的文化。Web 浏览器在访问服务器时包含显示其支持的文化的标头信息。ASP.Net 会自动将此信息放入 CultureInfo.CurrentUICulture。我们将其传递给 GetResourceSet 方法,然后该方法返回与当前浏览器设置匹配的资源集。

因此,如果浏览器设置为法语,将返回法语资源,并且仅返回法语资源。

陡峭 1.在 App_GlobalResources 文件夹中创建资源文件RLocalizedText.resx。并创建用所有字符串填充它。

步骤 2. 创建ResourcesController

using System.Web.Mvc;

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

陡峭 3.从 ResourcesController创建Index.cshtml视图

@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
    @:Resources.@res.Key = "@Html.Raw(
        HttpUtility.JavaScriptStringEncode(res.Value.ToString()))";
}
Run Code Online (Sandbox Code Playgroud)

选择你想要使用它的地方。

陡峭的4A(布局)。如果您想在整个站点上使用它,则需要将此脚本引用放在@RenderSection上的_Layout(共享视图)上

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

陡峭的4B(视图)。如果您只想在某些视图中查看。

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

陡峭 5. 现在是使用它的时候了。选择需要查看资源文件字符串的视图并放置此代码。

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

这就是所有的人!希望它能帮助别人!


Mob*_*ble 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>
Run Code Online (Sandbox Code Playgroud)

服务器端,大大简化了,但你明白了:

public ContentResult ResourceLabel(string labelKey) {
    return Content(ResourceClass.GetString(labelKey));
}
Run Code Online (Sandbox Code Playgroud)

  • 这是否会为每个标签向服务器创建一个单独的请求? (2认同)