在MVC 3访问资源文件 [英] Accessing Resource Files in MVC 3

查看:118
本文介绍了在MVC 3访问资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的资源文件访问键/值对的Java脚本和.cshtml意见。
有关我的一些CSHTML静态内容,我不想在我的模型来创建一个属性,因此这将是很好,如果我可以直接访问资源文件。

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.

推荐答案

您可以创建一个文件RESX并设置其属性为<一个href=\"http://www.developmentalmadness.com/archive/2009/05/20/aspnet-mvc-globalizationlocalization.aspx\">public,因为这里描述。

You can create a resx file and set its properties to public, as described here.

然后在你的 CSHTML 你可以使用:

Then on your cshtml you can use:

@Resources.ResNameHere.Property

要在JavaScript中使用简单地使其在剧本

To use on javascript simply render it on a script block

<script>
    var stringFromResource = "@Resources.ResNameHere.Property";
</script>

您也可以实现一个扩展方法 HTML 和读取从任何地方的资源,即使数据库,如果你需要的。

You can also implement an extension method to Html and read the resource from anywhere, even database if you need.

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")

这篇关于在MVC 3访问资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆