繁体   English   中英

将displayname属性作为参数传递

[英]Pass displayname property as parameter

对于以下ActionLink调用:

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

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

没有开箱即用的帮手。

但编写自定义文件非常容易:

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

是的,但它很难看。

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

您可能希望将其包装在扩展方法中。

伙计们有一个更简单的答案! 您只需要通过将“[0]”添加到“m => 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, })

小菜一碟!

嘿相当老的线程,但我得到了一个更好,更简单的答案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM