2012-05-15 52 views
4

對於下面的ActionLink調用:通DisplayName屬性作爲參數

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

我想在標籤中傳爲@ model.CustomerNumber產生,而不必通過它的「客戶編號」文本明確。對於參數是否存在@ Html.LabelFor(model => model.CustomerNumber)的equivilant?

回答

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

還有一個更簡單回答,夥計們!您只需要通過將「[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, }) 

小菜一碟!

1

嘿很老的線程,但我得到了這更好的和簡單的答案:

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