4

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?

4 Answers 4

3

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)
    }
)
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, but it's ugly.

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

You may want to wrap that in an extension method.

Comments

2

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!

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.