添加HtmlHelper以使用资源文件

时间:2017-05-10 17:24:39

标签: c# asp.net-mvc razor lambda

我正在尝试扩展HtmlHelper,以便它可以使用简单的资源文件从Linq实体转换字段名称。 问题是我无法获得扩展方法签名。代码如下:

public static class HtmlHelperExtension
{
    public static MvcHtmlString HeaderFromResource<TModel,
         TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
       ...
       return  (MvcHtmlString)html.Raw(something)
    }
}

当我尝试在视图中使用它时,像这样:

@model IEnumerable<WebApp.Models.TransferInConfig>
...
<th>
       @Html.HeaderFromResource(model => model.RemotePath) 
</th>

我收到以下错误:

  

&#39; IEnumerable的&#39;不包含的定义   &#39; RemotePath&#39;没有扩展方法&#39; RemotePath&#39;

2 个答案:

答案 0 :(得分:1)

开始你的模型是一个IEnumerable,它确实没有RemotePath定义,但它中的项目(可能)。因此,您必须首先遍历模型列表并使用每个项目。像这样的东西

foreach (var item in model){
   @Html.HeaderFromResource(item => item.RemotePath)  
}

答案 1 :(得分:0)

public static MvcHtmlString HeaderFromResource<TModel, TValue>( this HtmlHelper<IEnumerable<TModel>> html,   Expression<Func<TModel, TValue>> expression)
{
    var headerName = expression.Body.ToString() //return model.Connection.RemotePath
        .Split('.')
        .Last(); 

    if (Properties.Resources.ResourceManager.GetString(headerName) != null)
        headerName = Properties.Resources.ResourceManager.GetString(headerName);

    return MvcHtmlString.Create(headerName);           

我唯一需要做的就是查阅手册以获得DisplayForName的签名,但我不再使用它了。应该是从表达式获取字段名称的更好方法,无论如何这个适用于我。