将HtmlAttributes添加到模板

Jer*_*ose 9 html-helper asp.net-mvc-templates razor asp.net-mvc-3

如果我将HtmlAttributes传递给模板,如下所示:

@Html.DisplayFor(m => m.FirstName, new { htmlAttributes = new { @class = "orangetxt strongtxt" } })
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我如何将这些注入到我的HTML中:

<span @ViewData["htmlAttributes"]>@Model</span>
Run Code Online (Sandbox Code Playgroud)

这几乎可以工作,但它做了一些非常奇怪的事情,所以我假设这不是要走的路.

我意识到我可以通过HtmlHelper扩展方法实现这一点,以呈现完整的HTML元素(在本例中为span)并以这种方式传递属性,但是有没有办法直接将属性呈现为HTML元素,如上所述例?

Jer*_*ose 8

下面的扩展方法将允许我将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)))));
    }
Run Code Online (Sandbox Code Playgroud)

然后,要在标记内呈现它们,我可以这样做:

<span @Html.RenderHtmlAttributes(ViewData["htmlAttributes"])>@Model</span>
Run Code Online (Sandbox Code Playgroud)


小智 5

Jerad Rose 的回答很好,但我遇到了几个问题:

  • 它不会将下划线转换为属性名称中的破折号
  • 它不能优雅地处理无值属性

要解决第一个问题,请使用HtmlHelper.AnonymousObjectToHtmlAttributes.

以下是我对 Jerad 方法的修改:

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)))));
}
Run Code Online (Sandbox Code Playgroud)