简体   繁体   中英

C# MVC Resourcefile get string from variable

This is how I get a resource string in one of my views:

@MyProject.Resources.ResourceEN.MyResourceStringName
//Gives back mystring in desired language

What if I had a string variable that I wanted to send in?

@string HelloWorld;
@MyProject.Resources.ResourceEN.HelloWorld

This won't work obviously because it looks for the resource name "HelloWorld" and not the content of that string variable.

Is it somehow possible to use a variable for this?

You could use the ResourceManager's GetString method to return the value of the specified string resource using the variable:

@string HelloWorld;
@(new ResourceManager(typeof(MyProject.Resources.ResourceEN)).GetString(HelloWorld))

Or better yet consider adding a helper method/extension-method on HtmlHelper , something like:

public static string MyResource<T>(this HtmlHelper html, object key) {
    return new ResourceManager(typeof(T)).GetString(key.ToString());
}

which can then be used as follows:

@string HelloWorld;
@(Html.MyResource<MyProject.Resources.ResourceEN>(HelloWorld))

** EDIT **

Bear in mind that the MVC Razor parser sees < and thinks it's an HTML tag thus you need to wrap the call in parentheses to force it to treat the entire call as a single expression as above.

You can set the value to a variable like this:

@{ string HelloWorld = MyProject.Resources.ResourceEN.HelloWorld }

On a side note, it is unusual to specifically call out ResourceEN in your code. The culture is normally specified by setting the CurrentUICulture to the current thread and the call to MyProject.Resources will automatically select the correct language file based on the culture.

Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

It defaults to the culture that is set in the web.config file if not set explicitly within the current request.

<system.web>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-US" uiCulture="en-US"/>
</system.web>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM