将 HtmlAttributes 添加到模板

发布于 2024-12-11 04:40:51 字数 445 浏览 1 评论 0原文

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

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

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

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

这几乎可以工作,但它会做一些非常奇怪的事情,所以我假设这不是正确的方法。

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

If I am passing HtmlAttributes into a template, like this:

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

In my template, how would I inject these into my HTML:

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

This almost works, but it does some pretty weird stuff, so I'm assuming this isn't the way to go.

I realize I can accomplish this with an HtmlHelper extension method to render the full HTML element (span, in this case) and pass in the attributes that way, but is there a way to just render attributes straight into an HTML element, like the above example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

墟烟 2024-12-18 04:40:51

下面的扩展方法将允许我将 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>

The below extension method will allow me to convert HtmlAttributes to a string:

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

Then, to render them within the tag, I can just do this:

<span @Html.RenderHtmlAttributes(ViewData["htmlAttributes"])>@Model</span>
好多鱼好多余 2024-12-18 04:40:51

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

Jerad Rose's answer is good, but I ran into couple of issues with it:

  • It does not not convert underscores to dashes in attribute names
  • It does not handle no-value attributes gracefully

To address first issue, use HtmlHelper.AnonymousObjectToHtmlAttributes.

Below is my modification of Jerad's method:

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)))));
}
幸福丶如此 2024-12-18 04:40:51

试试这个,

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

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

Try this instead,

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

This will render a string, whereas your version did do weird stuff, rendered { } as part of the output.

冷清清 2024-12-18 04:40:51

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

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

一个例子。

如果您在 /Views/Shared 中有这样的 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。

仅供参考:例如,EditorFor() 的工作方式类似,但它使用 /EditorTemplates 文件夹。

DisplayFor() is used to render the template that matches the property type.

Display templates are .cshtml files inside /DisplayTemplates folder which in turn is inside a view folder (i.e. any folder from Home, Shared or even a specific controller).

An example.

If you've a String.cshtml template like this inside /Views/Shared:

@model String

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

Every time you call DisplayFor() for a string property:

DisplayFor(model => model.MyStringProperty);

It renders the template accordingly to the string's value. You can be more specific and put /DisplayTemplates inside a specific View folder and them only calls from those views are affected by the template.


In your case you can be even more specific and call DisplayFor() with a particular template.

Suppose you've a template for a particular property, called MyPropertyTemplate.cshtml. You would call DisplayFor() like this:

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

And them, inside that template you can have whatever HTML attributes you want.

@model MyProperty

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

PS: When it doesn't find a template I guess it only calls model.Property.ToString() without additional html.

FYI: EditorFor(), for example, works in a similar way but it uses /EditorTemplates folder.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文