C# MVC Resourcefile get string from variable

Ref*_*eft 2 c# asp.net-mvc resources

这就是我在其中一个视图中获取资源字符串的方式:

@MyProject.Resources.ResourceEN.MyResourceStringName
//Gives back mystring in desired language
Run Code Online (Sandbox Code Playgroud)

如果我有一个想要发送的字符串变量怎么办?

@string HelloWorld;
@MyProject.Resources.ResourceEN.HelloWorld
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,因为它查找资源名称“HelloWorld”而不是该字符串变量的内容。

是否有可能为此使用变量?

chr*_*dam 5

您可以使用ResourceManager 的 GetString方法通过变量返回指定字符串资源的值:

@string HelloWorld;
@(new ResourceManager(typeof(MyProject.Resources.ResourceEN)).GetString(HelloWorld))
Run Code Online (Sandbox Code Playgroud)

或者更好地考虑在 上添加辅助方法/扩展方法HtmlHelper,例如:

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

然后可以按如下方式使用:

@string HelloWorld;
@(Html.MyResource<MyProject.Resources.ResourceEN>(HelloWorld))
Run Code Online (Sandbox Code Playgroud)

**编辑**

请记住,MVC Razor 解析器会看到<并认为它是一个 HTML 标记,因此您需要将调用包装在括号中以强制它将整个调用视为如上所述的单个表达式。