Display displayname property as parameter

For the next ActionLink call:

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

I am trying to pass a shortcut to @ model.CustomerNumber to create the text "Customer Number" instead of passing it explicitly. Is there any equivilant from @ Html.LabelFor (model => model.CustomerNumber) for the parameters?

+4
source share
4 answers

There is no such assistant out of the box.

But trivially easy to write custom:

 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 creating the namespace in which you defined it in scope):

 @Html.ActionLink( "Customer Number", "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, customerNumberDescription = Html.DisplayNameFor(model => model.CustomerNumber) } ) 
+3
source

Yes, but it's ugly.

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

You can wrap this in an extension method.

+2
source

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

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

To add it to 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!

+2
source

Hey, a 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, }) 
+1
source

Source: https://habr.com/ru/post/1412594/


All Articles