将HtmlAttributes添加到模板

时间:2011-10-19 23:57:06

标签: asp.net-mvc-3 razor html-helper asp.net-mvc-templates

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

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

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

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

这几乎可以工作,但它确实有些奇怪的东西,所以我假设这不是可行的方法。

我意识到我可以使用HtmlHelper扩展方法来完成此操作以呈现完整的HTML元素(在本例中为span)并以这种方式传递属性,但是有没有办法直接将属性呈现为HTML元素,像上面的例子一样?

4 个答案:

答案 0 :(得分: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)))));
    }

然后,为了在标签内呈现它们,我可以这样做:

<span @Html.RenderHtmlAttributes(ViewData["htmlAttributes"])>@Model</span>

答案 1 :(得分:4)

杰拉德·罗斯的答案很好,但我遇到了几个问题:

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

要解决第一个问题,请使用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)))));
}

答案 2 :(得分:1)

试试这个,

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

这将呈现一个字符串,而您的版本确实做了奇怪的事情,将{ }作为输出的一部分进行渲染。

答案 3 :(得分:0)

DisplayFor()用于呈现与属性类型匹配的模板。

显示模板是 / DisplayTemplates 文件夹中的.cshtml文件,而该文件又位于视图文件夹中(即来自Home,Shared或甚至特定控制器的任何文件夹)。

一个例子。

如果你在 / Views / Shared 中有 String.cshtml 这样的模板:

@model String

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

每次为{1}}调用字符串属性时:

DisplayFor()

它将模板相应地呈现为字符串的值。您可以更具体,将 / DisplayTemplates 放在特定的View文件夹中,只有来自这些视图的调用才会受到模板的影响。


在您的情况下,您可以更加具体,并使用特定模板致电DisplayFor(model => model.MyStringProperty);

假设您有一个名为MyPropertyTemplate.cshtml的特定属性的模板。你可以这样打电话给DisplayFor()

DisplayFor()

他们,在该模板中,你可以拥有你想要的任何HTML属性。

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

PS:如果找不到模板,我猜它只会在没有附加html的情况下调用@model MyProperty <span class="orangetxt strongtxt">@MyProperty.ToString()</span>

仅供参考:model.Property.ToString(),以类似的方式工作,但它使用 / EditorTemplates 文件夹。