【问题标题】:Passing an object to HTML attributes将对象传递给 HTML 属性
【发布时间】:2011-09-20 01:30:19
【问题描述】:

如何将对象传递给 HTML 属性? 例如我有以下代码:

var attrs = new { id = "myid", style = "color: Red;" };

如何像这样将 attrs 转换为字符串以将它们嵌入到 HTML 标记中:

id="myid" style="color: Red;"

提前致谢:)

【问题讨论】:

  • 感谢您的提问!我拯救了我的一天!

标签: c# asp.net html asp.net-mvc-3


【解决方案1】:

令人惊讶的是,RouteValueDictionary 类提供了此功能:

IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs);

然后,您可以将此字典与 TagBuilder 结合使用,您可能仍然会使用它:

var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.ToString(TagRenderMode.Normal);

您可以在 ASP.NET MVC 源代码本身中看到这一点; TextAreaExtensions.cs 是一个比较简单的例子。

编辑:

为了正确地将“data_attr”转换为“data-attr”,请使用AnonymousObjectToHtmlAttributes静态方法。

IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);

【讨论】:

  • 只需使用属性 data_bind 尝试此操作,输出为 data_bind 而不是预期的 data-bind - 有什么想法吗?
  • 不幸的是,TextAreaExtensions 的 URL 不再有效 :) 只是让您知道。
  • 有一个替代方法,System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(),它可能更合适;它以与标准 MVC Html 帮助程序相同的方式用连字符替换下划线
  • 这个答案已经过时了。正确的方法应该是HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),它将正确处理data_blah类型属性。
【解决方案2】:

您不需要转换为字符串。 HTML Helpers 的最后一个参数是一个对象。 你只需像上面写的那样给它对象:

例如

@Html.TextBoxFor(x => x.Foo, new { size = 10, maxlength = 10 }) 
@Html.TextAreaFor(x => x.Notes, new { @class = "additionalInfo" })
@Html.TextBoxFor(x=>x.Registration.Address.Postcode, new {type="number", @class="postcode numeric", size=5, maxlength=5})

在旁注中,您可能不应该直接在 HTML 中设置样式,而是使用 CSS 类/选择器来代替单独的样式表。 此外,当您使用 MVC HTML 帮助器时,应该自动设置每个 DOM 元素的 ID

【讨论】:

  • 我知道,但除此之外,我想编写自己的方法来呈现另一个表单组件,所以我需要一种像 MVC 3 那样的方法:)
  • np 你可能应该在你的问题中提到这一点
【解决方案3】:

以下是如何进行此转换:

var htmlAttributes = new { id="myid", @class="myclass" };

string string_htmlAttributes = "";
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
  string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}

PropertyDescriptor属于System.ComponentModel

【讨论】:

  • 不知道为什么这不是推荐的答案。
  • 代码没问题,有一个重要的变化:使用 HttpUtility.HtmlAttributeEncode 来渲染属性值。
  • 还将标签名称 x_y 转换为 x-y。 TagBuilder 就是这样做的。
猜你喜欢
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2019-06-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
相关资源
最近更新 更多