Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将displayname属性作为参数传递_C#_Asp.net_.net_Asp.net Mvc 3 - Fatal编程技术网

C# 将displayname属性作为参数传递

C# 将displayname属性作为参数传递,c#,asp.net,.net,asp.net-mvc-3,C#,Asp.net,.net,Asp.net Mvc 3,对于以下ActionLink调用: @Html.ActionLink("Customer Number", "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, }) 我正在尝试传入@model.CustomerNumber的标签,以生成“Customer Number”文本,而不必显式传入它。参数是否有@Html.LabelFor(model=>model

对于以下ActionLink调用:

@Html.ActionLink("Customer Number", "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })
我正在尝试传入@model.CustomerNumber的标签,以生成“Customer Number”文本,而不必显式传入它。参数是否有@Html.LabelFor(model=>model.CustomerNumber)的等价项

是的,但是很难看

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

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

没有现成的帮助程序

但是编写一个定制的很简单:

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

有一个更简单的答案,伙计们!只需将“[0]”添加到“m=>m.CustomerNumber”即可引用第一行索引值!(是的,即使没有值行,这也会起作用!)

要将其放在您的操作链接中:

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