自定义 HTML 助手:如何获取 lambda 表达式的值?

Custom HTML helper : how do I get the value of the lambda expression?

我想创建一个自定义 HTML 帮助器(图像),用于 mvc5 应用程序的视图。它将使用 lambda 表达式调用,就像开箱即用的助手 EditorFor

@Html.EditorFor(model => model.Name)
@Html.Image(model => model.ImagePath)

下面是我的空帮手。我需要获取 model.ImagePath 变量的值(以创建 img-tag)。这是怎么做到的? (我已经知道如何创建助手的其余部分了)

public static IHtmlString Image<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> imagePath) {

}

您可以从 ModelMetadata 阅读它。请注意,由于您的扩展方法使用 lambda,因此约定名称应为 ImageFor()

public static IHtmlString ImageFor<TModel, TValue>(this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> imagePath)
{
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    // Get the property name
    string name = ExpressionHelper.GetExpressionText(expression);
    // Get the property type
    Type type = metadata.ModelType;
    // Get the property value
    object value = metadata.Model;

请注意,如果您希望模型始终为 string,则签名可以为

public static IHtmlString ImageFor<TModel>(this HtmlHelper<TModel> html,
    Expression<Func<TModel, string>> imagePath)