Accessing Resource Files in MVC 3

I want to get a 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 access the resource files directly.

+5
source share
3 answers

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

Then on cshtmlyou can use:

@Resources.ResNameHere.Property

To use on javascript just render it on a block script

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

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);
}

@Html.Resource("Key")
+14

Razor . ?

0

, / JavaScript .cshtml.

.cshtml

@Html.ActionLink("New Contact", null, null, null, new { id = "general", Href = "#", @Newtitle = @Resources.General.Newtitle })

Name      Value
----      -----
Newtitle  New title Value

JavaScript

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

.

0

All Articles