从自定义帮助器方法访问System.Web.Mvc下的MvcResources

问题描述 投票:0回答:2

我正在使用MVC 5.0开发一个自定义的Html辅助扩展方法,在浏览了内置辅助方法的源代码之后:InputHelper(),我想在我的帮助方法中使用它的一部分:

if (String.IsNullOrEmpty(fullName))
{
    throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
}

但是,即使使用了名称空间System.Web.Mvc,我仍然会收到错误消息:在当前上下文中找不到名称“MvcResources”。

根据其源代码,MvcResources在.resx文件中定义:https://github.com/ASP-NET-MVC/aspnetwebstack/blob/4e40cdef9c8a8226685f95ef03b746bc8322aa92/src/System.Web.Mvc/Properties/MvcResources.resx

我相信我上面分享的源代码是MVC 5.x.

那么,任何人都可以帮忙吗?谢谢。

asp.net-mvc html-helper
2个回答
0
投票

您可以使用System.Resources.ResourceManager获取资源。

所以您的代码如下所示 -

if (String.IsNullOrEmpty(fullName))
{    
    throw new ArgumentException(System.Resources.ResourceManager(typeof(MyProject.MvcResources)).GetString("name"),"name");//replace `MyProject.MvcResources` by full name (with namspace) of your Resource class
}

您可以创建和用户自定义HtmlHelper,如下所示。

例:

帮手:

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

使用:

@Html.InputHelper<MyProject.Resouce.MyResouce>("name")

希望它对你有所帮助。


0
投票

是的,这篇文章是旧的,但今天在搜索时出现了我正在寻找System.Web.Mvc.Properties.MvcResources的实际resx文件(所以我可以在其中复制一个值)

您无法直接访问System.Web.Mvc.Properties.MvcResources的原因是它被声明为内部。

© www.soinside.com 2019 - 2024. All rights reserved.