对于以下ActionLink调用:
@Html.ActionLink("Customer Number", "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })
我试图传递@ model.CustomerNumber的标签来生成"客户编号"文本而不是必须明确传递它。对于参数,是否存在@ Html.LabelFor(model => model.CustomerNumber)的等效项?
答案 0 :(得分:3)
没有开箱即用的帮手。
但编写自定义文章非常容易:
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()));
}
}
然后使用它(在将你定义它的命名空间带入范围之后):
@Html.ActionLink(
"Customer Number",
"Search",
new {
Search = ViewBag.Search,
q = ViewBag.q,
sortOrder = ViewBag.CustomerNoSortParm,
customerNumberDescription = Html.DisplayNameFor(model => model.CustomerNumber)
}
)
答案 1 :(得分:2)
是的,但它太丑了。
ModelMetadata.FromLambdaExpression(m => m.CustomerNumber, ViewData).DisplayName
您可能希望将其包装在扩展方法中。
答案 2 :(得分:2)
有一个更简单的答案,伙计们!您只需要通过将“[0]”添加到“m =&gt; m.CustomerNumber”来引用第一行索引值! (并且,是的,即使没有值的行,这也会起作用!)
Html.DisplayNameFor(m => m[0].CustomerNumber).ToString()
将其放入您的操作链接:
@Html.ActionLink(Html.DisplayNameFor(m => m[0].CustomerNumber).ToString(), "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })
一块蛋糕!
答案 3 :(得分:1)
嘿,相当老的帖子,但我得到了一个更好,更简单的答案:
@Html.ActionLink(Html.DisplayNameFor(x=>x.CustomerName), "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })