gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:54:48 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com