簡體   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