将对象传递给HTML属性

Hie*_*ung 43 html c# asp.net asp.net-mvc-3

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

var attrs = new { id = "myid", style = "color: Red;" };
Run Code Online (Sandbox Code Playgroud)

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

id="myid" style="color: Red;"
Run Code Online (Sandbox Code Playgroud)

提前致谢 :)

Dom*_*nic 72

令人惊讶的是,该功能由RouteValueDictionary该类提供:

IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs);
Run Code Online (Sandbox Code Playgroud)

然后,您可以将此词典与a一起使用TagBuilder,您可能会使用它:

var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.ToString(TagRenderMode.Normal);
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
Run Code Online (Sandbox Code Playgroud)

  • 有一个替代方案,System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(),这可能更合适; 它以与标准MVC Html助手相同的方式用连字符替换下划线 (12认同)
  • 这个答案已经过时了.正确的方法应该是`HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)`,它将正确处理`data_blah`类型属性. (3认同)
  • 只是尝试使用属性data_bind,输出是data_bind而不是预期的数据绑定 - 任何想法? (2认同)

Dav*_*veo 23

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

例如

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

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


Cht*_*lek 6

以下是如何进行此转换:

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

PropertyDescriptor 属于班级 System.ComponentModel

  • 不知道为什么这不是推荐的答案. (2认同)