Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass displayname property as parameter

For the following ActionLink call:

@Html.ActionLink("Customer Number", "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })

I'm trying to pass in the label for @model.CustomerNumber to generate the "Customer Number" text instead of having to pass it in explicitly. Is there an equivilant of @Html.LabelFor(model => model.CustomerNumber ) for parameters?

like image 810
stats101 Avatar asked Feb 21 '23 11:02

stats101


1 Answers

There is no such helper out of the box.

But it's trivially easy to write a custom one:

public static class HtmlExtensions
{
    public static string DisplayNameFor<TModel, TProperty>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TProperty>> expression
    )
    {
        var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        return (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new[] { '.' }).Last()));
    }
}

and then use it (after bringing the namespace in which you defined it into scope):

@Html.ActionLink(
    "Customer Number", 
    "Search", 
    new { 
        Search = ViewBag.Search, 
        q = ViewBag.q, 
        sortOrder = ViewBag.CustomerNoSortParm, 
        customerNumberDescription = Html.DisplayNameFor(model => model.CustomerNumber)
    }
)
like image 177
Darin Dimitrov Avatar answered Feb 27 '23 23:02

Darin Dimitrov