【问题标题】:Lambda Expression compiling with parameter带参数的 Lambda 表达式编译
【发布时间】:2013-04-15 14:39:53
【问题描述】:

我想用助手扩展 MVC。假设我想构建一个扩展方法,该方法从模型中获取一个属性并呈现一个段落。

我已经编写了这段代码,但它不会编译。我不知道该怎么做:

public static class PExtension
{
    public static string PFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) where TModel: class 
    {
        var f = expression.Compile();
        // won't compile the line below:
        string propretyValue = f();
        return "<p>" + propretyValue + "</p>";
    }
}

为了记录,我的观点应该使用类似的东西:

@Html.PFor(m => m.Description);

谢谢。

编辑

错误描述:*Delegate 'Func' does not take 0 arguments*

【问题讨论】:

    标签: asp.net-mvc lambda extension-methods func


    【解决方案1】:

    表达式参数指定表达式的返回值为 TValue,但您试图将编译后的表达式的返回值分配给字符串。我猜编译错误是关于“无法将 TValue 转换为字符串”?

    试试这个:

    object propertyValue = f();
    return string.Format( "<p>{0}</p>", propertyValue != null ? propertyValue.ToString() : string.Empty );
    

    更新:

    您发布的错误表明您需要将模型对象传递给表达式才能对其进行评估。在查看ASP.NET MVC source code 以了解他们如何执行扩展方法时,他们从 ViewData 中获取模型,如下所示:

    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    

    所以试试这个:

    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    object propertyValue = f((TModel)metadata.Model);
    return string.Format( "<p>{0}</p>", propertyValue != null ? propertyValue.ToString() : string.Empty );
    

    【讨论】:

    • 太好了,我会发布一个稍微更正的答案,但你指出了我正确的方向。谢谢。
    【解决方案2】:

    最后,代码如下:

     public static class PExtension
        {
            public static MvcHtmlString PFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) where TModel : class
            {
                ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    
                return MvcHtmlString.Create(string.Format("<p>{0}</p>", metadata.Model != null ? metadata.Model.ToString() : string.Empty));
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多