【问题标题】:Custom HTML helper : how do I get the value of the lambda expression?自定义 HTML 助手:如何获取 lambda 表达式的值?
【发布时间】:2018-03-28 17:07:12
【问题描述】:

我想创建一个自定义 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) {

}

【问题讨论】:

    标签: c# asp.net-mvc lambda html-helper


    【解决方案1】:

    您可以从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)
    

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多