2
我一直在使用资源文件并在标准方式下在我的视图中引用它们,例如Resources.Labels.CountryName
。但我有一个情况我需要从资源名称获取资源的价值在我的C#作为一个字符串即如何从它的字符串名称获取资源的值
string resourceName = "Resource.Labels.CountryName";
我怎么会得到从这个字符串资源文件中的值?
我一直在使用资源文件并在标准方式下在我的视图中引用它们,例如Resources.Labels.CountryName
。但我有一个情况我需要从资源名称获取资源的价值在我的C#作为一个字符串即如何从它的字符串名称获取资源的值
string resourceName = "Resource.Labels.CountryName";
我怎么会得到从这个字符串资源文件中的值?
通常,您会资源,
GetLocalResourceObject("~/VirtualPath", "ResourceKey");
GetGlobalResourceObject("ClassName", "ResourceKey");
您可以适应这一点。我写我自己扩展的HTML帮助这样一个全球资源:
public static string GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
{
var resource = htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey);
return resource != null ? resource.ToString() : string.Empty;
}
我认为,在这个你的榜样,你会得到的资源与@Html.GetGlobalResource("Labels", "CountryName")
你的看法。
由于当地资源所需要的虚拟路径,我不希望它被写入到视图,我用这个组合,这给双方机会:
public static string GetLocalResource(this HtmlHelper htmlHelper, string virtualPath, string resourceKey)
{
var resource = htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(virtualPath, resourceKey);
return resource != null ? resource.ToString() : string.Empty;
}
public static string Resource(this HtmlHelper htmlHelper, string resourceKey)
{
var virtualPath = ((WebViewPage) htmlHelper.ViewDataContainer).VirtualPath;
return GetLocalResource(htmlHelper, virtualPath, resourceKey);
}
有了,你可以得到一个本地资源非常在你看来,写作@Html.Resource("Key")
很舒服。或者使用第一种方法获取其他视图的本地资源,如@Html.GetLocalResource("~/Views/Home/AnotherView.cshtml", "Key")
。
综合答案,谢谢...有一点点麻烦,因为我没有在App_GlobalResources中的资源文件,而是在内容/资源中,但已设法让它现在工作。 – user517406 2013-04-08 13:24:20