Search code examples
c#asp.net-mvclambdahtml-helper

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


I want to create a custom HTML helper (Image) that is used in views of a mvc5 app. It is going to be called with a lambda expression, just like the out-of-the-box helper EditorFor

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

Below is the empty helper I have. I need to get the value of the model.ImagePath variable (to create the img-tag). How is that done ? (I already know how to create the rest of the helper)

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

}

Solution

  • Your can read it from the ModelMetadata. Note that since your extension method uses a lambda, convention is that its name should be 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;
    

    Note if you want the the model to always be string, then the signature can be

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