10

次のように、HtmlAttributesをテンプレートに渡す場合:

@Html.DisplayFor(m => m.FirstName, new { htmlAttributes = new { @class = "orangetxt strongtxt" } })

私のテンプレートでは、これらをHTMLにどのように挿入しますか?

<span @ViewData["htmlAttributes"]>@Model</span>

これはほとんど機能しますが、かなり奇妙なことをするので、これは道ではないと思います。

HtmlHelper拡張メソッドを使用してこれを実現し、完全なHTML要素(この場合はspan)をレンダリングして、その方法で属性を渡すことができますが、上記のように、属性をHTML要素に直接レンダリングする方法はありますか?例?

4

4 に答える 4

9

以下の拡張メソッドを使用すると、HtmlAttributesを文字列に変換できます。

    public static MvcHtmlString RenderHtmlAttributes<TModel>(
        this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
    {
        var attrbituesDictionary = new RouteValueDictionary(htmlAttributes);

        return MvcHtmlString.Create(String.Join(" ", 
            attrbituesDictionary.Select(
                item => String.Format("{0}=\"{1}\"", item.Key, 
                htmlHelper.Encode(item.Value)))));
    }

次に、タグ内でそれらをレンダリングするために、これを行うことができます:

<span @Html.RenderHtmlAttributes(ViewData["htmlAttributes"])>@Model</span>
于 2011-10-20T14:01:46.010 に答える
5

Jerad Roseの答えは良いですが、いくつかの問題に遭遇しました:

  • 属性名のアンダースコアをダッシュ​​に変換しません
  • 値のない属性を適切に処理しません

最初の問題に対処するには、 を使用しますHtmlHelper.AnonymousObjectToHtmlAttributes

以下は、ジェラドの方法の私の修正です:

public static MvcHtmlString RenderHtmlAttributes(this HtmlHelper helper, object htmlAttributes)
{
        if (htmlAttributes == null) return new MvcHtmlString(String.Empty);
        var attrbituesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        return new MvcHtmlString(String.Join(" ", attrbituesDictionary.Select(item => string.IsNullOrEmpty((string)item.Value) ? String.Format("{0}", item.Key) : String.Format("{0}=\"{1}\"", item.Key, helper.Encode(item.Value)))));
}
于 2014-08-14T16:44:59.117 に答える
0

DisplayFor()プロパティ タイプに一致するテンプレートをレンダリングするために使用されます。

表示テンプレートは、 /DisplayTemplatesフォルダー内の .cshtml ファイルであり、ビュー フォルダー (つまり、ホーム、共有、または特定のコントローラーの任意のフォルダー) 内にあります。

例。

/Views/Shared内に次のようなString.cshtmlテンプレートがある場合:

@model String

@if (string.IsNullOrEmpty(Model)) {
   <span>(no string)</span>
}
else {
   <span>@Model</span>
}

DisplayFor()文字列プロパティを呼び出すたびに:

DisplayFor(model => model.MyStringProperty);

文字列の値に応じてテンプレートをレンダリングします。より具体的に/DisplayTemplatesを特定の View フォルダー内に配置すると、それらのビューからの呼び出しのみがテンプレートの影響を受けます。


あなたの場合、さらに具体的にDisplayFor()特定のテンプレートで呼び出すことができます。

MyPropertyTemplate.cshtml という特定のプロパティのテンプレートがあるとします。DisplayFor()次のように呼び出します。

DisplayFor(model => model.MyProperty, "MyPropertyTemplate");

そして、そのテンプレート内に、必要な HTML 属性を含めることができます。

@model MyProperty

<span class="orangetxt strongtxt">@MyProperty.ToString()</span>

model.Property.ToString()PS: テンプレートが見つからない場合は、 html を追加せずに呼び出すだけだと思います。

参考までに:EditorFor()たとえば、 は同様の方法で機能しますが、/EditorTemplatesフォルダーを使用します。

于 2011-10-20T01:09:18.320 に答える