如果我将 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>

其他提示

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)))));
}

尝试此相反,

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

这会使一个字符串,而你的版本没有做怪异的东西,呈现{ }作为输出的一部分。

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

显示模板的 / DisplayTemplates 夹这又是一个视图文件夹内(即任何从家,共享文件夹或甚至特定的控制器)的内部.cshtml文件。

一个例子。

如果您已经在 String.cshtml 的模板,像这里面的 /查看/共享的:

@model String

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

每次调用的字符串属性DisplayFor()时间:

DisplayFor(model => model.MyStringProperty);

有相应渲染模板到字符串的值。您可以更具体,并把的 / DisplayTemplates 的内部的特定视图文件夹,并从这些观点是由模板影响了他们唯一的要求。


在你的情况,你可以更加具体和呼叫DisplayFor()与特定的模板。

假设你已经为一个特定的属性,称为MyPropertyTemplate.cshtml模板。你会打电话DisplayFor()这样的:

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

和他们,模板里面你可以有任何HTML属性你想要的。

@model MyProperty

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

PS:当它没有找到一个模板,我想这只是调用model.Property.ToString()没有额外的HTML

FYI:EditorFor(),例如,工作在一个类似的方式,但它使用的 / EditorTemplates 文件夹

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top