Asp.net-Mvc-3

將 HtmlAttributes 添加到模板

  • September 7, 2015

如果我將 HtmlAttributes 傳遞給模板,如下所示:

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

在我的模板中,我將如何將這些注入到我的 HTML 中:

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

這幾乎可行,但它做了一些非常奇怪的事情,所以我假設這不是要走的路。

我意識到我可以使用 HtmlHelper 擴展方法來呈現完整的 HTML 元素(在本例中為跨度)並以這種方式傳遞屬性,但是有沒有辦法將屬性直接呈現到 HTML 元素中,就像上面一樣例子?

下面的擴展方法將允許我將 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>

引用自:https://stackoverflow.com/questions/7829643