Accessing Resource Files in MVC 3
17,334
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")
Author by
Vivek
Updated on August 14, 2022Comments
-
Vivek over 1 year
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.
-
Vivek about 13 yearsNot sure about this.could you please shed some more light on it. my resource files are in App_GlobalResources Folder.
-
marcind about 13 yearsCould you provide more information? What files do you have in your App_GlobalResources folder, how are you trying to access the resources, and what kind of failure are you seeing?