Accessing Resource Files in MVC 3

末鹿安然 提交于 2019-12-21 04:54:14

问题


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.


回答1:


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

Then on your cshtml you can use:

@Resources.ResNameHere.Property

To use on javascript simply render it on a script block

<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.

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



回答2:


You should be able to access the resource from a Razor view via the generated proxy class. Is that not working for you?




回答3:


Let us consider the following situation when we want to access key/value pair from the resource files in JavaScript and .cshtml views.

Inside .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

$('#general').click(function (evt) {
    alert($(this).attr("Newtitle"));
    evt.preventDefault();
});

Thanks.



来源:https://stackoverflow.com/questions/5673070/accessing-resource-files-in-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!