stats101
stats101

Reputation: 1877

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?

Upvotes: 4

Views: 1737

Answers (4)

Nikitesh
Nikitesh

Reputation: 1305

Hey pretty old thread but i got a better and simple answer for this:

@Html.ActionLink(Html.DisplayNameFor(x=>x.CustomerName), "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })

Upvotes: 1

Bob Quinn
Bob Quinn

Reputation: 139

There's a much simpler answer, guys! You just need to reference the first row indexed value by adding "[0]" to "m => m.CustomerNumber"! (And, yes, this will work even if there are no rows of values!)

 Html.DisplayNameFor(m => m[0].CustomerNumber).ToString()

To put it in your action link:

@Html.ActionLink(Html.DisplayNameFor(m => m[0].CustomerNumber).ToString(), "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })

Piece of cake!

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

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)
    }
)

Upvotes: 3

SLaks
SLaks

Reputation: 887453

Yes, but it's ugly.

ModelMetadata.FromLambdaExpression(m => m.CustomerNumber, ViewData).DisplayName

You may want to wrap that in an extension method.

Upvotes: 2

Related Questions