4

次の ActionLink 呼び出しの場合:

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

@model.CustomerNumber のラベルを渡して、明示的に渡すのではなく、「顧客番号」テキストを生成しようとしています。パラメータに @Html.LabelFor(model => model.CustomerNumber ) と同等のものはありますか?

4

4 に答える 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)
    }
)
于 2012-05-15T13:49:27.400 に答える
2

はい、でも醜いです。

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

それを拡張メソッドでラップしたい場合があります。

于 2012-05-15T13:47:48.803 に答える
1

かなり古いスレッドですが、これに対するより良いシンプルな答えが得られました。

@Html.ActionLink(Html.DisplayNameFor(x=>x.CustomerName), "Search", new { Search = ViewBag.Search, q = ViewBag.q, sortOrder = ViewBag.CustomerNoSortParm, })
于 2014-06-24T07:06:32.547 に答える