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?
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)
}
)
Yes, but it's ugly.
ModelMetadata.FromLambdaExpression(m => m.CustomerNumber, ViewData).DisplayName
You may want to wrap that in an extension method.
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!
嘿相当老的线程,但我得到了一个更好,更简单的答案:
@Html.ActionLink(Html.DisplayNameFor(x=>x.CustomerName), "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.