javascript 在 MVC 3 中访问资源文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5673070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing Resource Files in MVC 3
提问by Vivek
I want to to access key/value pair from my resource files in java script and .cshtml views. For some static content on my cshtml i don't want to create a property in my model so it would be nice if i could directly access resource files.
我想在 java 脚本和 .cshtml 视图中从我的资源文件访问键/值对。对于我的 cshtml 上的一些静态内容,我不想在我的模型中创建一个属性,所以如果我可以直接访问资源文件会很好。
回答by BrunoLM
You can create a resx file and set its properties to public, as described here.
您可以创建 resx 文件并将其属性设置为public,如此处所述。
Then on your cshtml
you can use:
然后cshtml
你可以使用:
@Resources.ResNameHere.Property
To use on javascript simply render it on a script
block
要在 javascript 上使用,只需将它呈现在一个script
块上
<script>
var stringFromResource = "@Resources.ResNameHere.Property";
</script>
You can also implement an extension method to Html
and read the resource from anywhere, even database if you need.
您还可以实现扩展方法Html
并从任何地方读取资源,如果需要,甚至是数据库。
public static MvcHtmlString Resource<T>(this HtmlHelper<T> html, string key)
{
var resourceManager = new ResourceManager(typeof(Website.Resources.ResNameHere));
var val = resourceManager.GetString(key);
// if value is not found return the key itself
return MvcHtmlString.Create(String.IsNullOrEmpty(val) ? key : val);
}
Then you can call as
然后你可以调用
@Html.Resource("Key")
回答by marcind
You should be able to access the resource from a Razor view via the generated proxy class. Is that not working for you?
您应该能够通过生成的代理类从 Razor 视图访问资源。这不适合你吗?
回答by Nawaz
Let us consider the following situation when we want to access key/value pair from the resource files in JavaScript and .cshtml views.
当我们想从 JavaScript 和 .cshtml 视图中的资源文件访问键/值对时,让我们考虑以下情况。
Inside .cshtml
.cshtml 内
@Html.ActionLink("New Contact", null, null, null, new { id = "general", Href = "#", @Newtitle = @Resources.General.Newtitle })
where the resource file is containing following data
其中资源文件包含以下数据
Name Value
---- -----
Newtitle New title Value
Now you are ready to use your resource data
现在您已准备好使用您的资源数据
Inside JavaScript
JavaScript 内部
$('#general').click(function (evt) {
alert($(this).attr("Newtitle"));
evt.preventDefault();
});
Thanks.
谢谢。