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

标签 javascript asp.net asp.net-mvc localization

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

最佳答案

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

We don’t have to do much to determine what culture to use. The web browser, when it hits the server, includes header information showing what cultures it supports. ASP.Net automatically puts this information into CultureInfo.CurrentUICulture. We pass this into the GetResourceSet method, which then returns the resource set that matches the current browser settings.

Thus, if the browser is set to French, the French resources, and only the French Resources, will be returned.

Steep 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();
        }
    }
}

Steep 3. 从 ResourcesController 创建 Index.cshtml View

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

选择您想要使用它的位置。

《Steep 4A》(布局)。如果您想在整个网站上使用它,则需要将此脚本引用放在@RenderSection上的_Layout(共享 View )上

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

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

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

《极限巅峰》5。现在是使用它的时候了。选择一个您需要查看资源文件中的字符串的 View 并放置此代码。

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

这就是大家!希望对其他人有帮助!

关于javascript - 在 ASP.NET MVC 中向 JavaScript 文件公开资源字符串的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16122791/

相关文章:

javascript - 返回 Mongoose 模型函数的结果

javascript - 数据表简要显示页面加载和刷新时删除的行

javascript - 使用 json 中的 javascript 检索总数

html - 使 ajax TabPanel 的背景半透明

ASP.NET Core 6 - 从 swagger explorer 中隐藏最小的 api 端点

c# - 在 asp .net 中处理异常

c# - 模型中属性的正则表达式验证

javascript - JSHint 错误 : "E001 - Bad option"

c# - 入口点在没有构建 IHost 的情况下退出

c# - MVC 添加和删除子集合中的项目