将displayname属性作为参数传递

4

对于以下的ActionLink调用:

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

我正在尝试传递@model.CustomerNumber的标签,以生成“客户号码”文本,而不是必须明确传递它。是否有与参数等效的@Html.LabelFor(model => model.CustomerNumber)?

我试图通过@model.CustomerNumber的标签来生成“客户号码”文本,而不是必须明确传递它。是否有类似于@Html.LabelFor(model => model.CustomerNumber)的参数等效项?

4个回答

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

2

可以,但是不够美观。

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

你可能需要将其包装在扩展方法中。


2

大家好,这里有一个更简单的答案!只需要在“m => m.CustomerNumber”后面加上“[0]”,就可以引用第一行索引值了!(是的,即使没有任何行的值,这也适用!)

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

小菜一碟!

1

嘿,这是一个很老的帖子,但我有一个更好和更简单的答案:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接