简体   繁体   English

将对象传递给HTML属性

[英]Passing an object to HTML attributes

How to pass an object to HTML attributes? 如何将对象传递给HTML属性? For example I have the following code: 例如,我有以下代码:

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

How to convert attrs to string like this to embed them into an HTML markup: 如何将attrs转换为这样的字符串以将其嵌入HTML标记中:

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

Thanks in advance :) 提前致谢 :)

This functionality is, surprisingly enough, provided by the RouteValueDictionary class: 令人惊讶的是, RouteValueDictionary类提供了此功能:

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

You can then use this dictionary in conjunction with a TagBuilder , which you will probably be using anyway: 然后,您可以将此字典与TagBuilder结合使用,无论如何您都可能会使用它:

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

You can see this done in the ASP.NET MVC source code itself; 您可以在ASP.NET MVC源代码本身中看到这一点; one of the simpler examples is in TextAreaExtensions.cs . TextAreaExtensions.cs是更简单的示例之一。

EDIT: 编辑:

In order to properly convert "data_attr" to "data-attr", use the AnonymousObjectToHtmlAttributes static method. 为了正确地将“ data_attr”转换为“ data-attr”,请使用AnonymousObjectToHtmlAttributes静态方法。

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

You do not need to convert to a string. 您不需要转换为字符串。 The last paramater for HTML Helpers is an Object. HTML帮助器的最后一个参数是一个对象。 You just give it the object like you have written above: 您只需像上面写的那样给它对象:

For exmample 例如

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

on a side note you probably should not be setting styles directy inline with your HTML and use a CSS class/selector instead with a seperate style sheet. 另外,您可能不应该直接在HTML中直接设置样式,而应使用CSS类/选择器以及单独的样式表。 Also the ID of each DOM element should automatically be set when you use MVC HTML helpers 此外,使用MVC HTML帮助器时,应自动设置每个DOM元素的ID。

Here's how to do this conversion : 这是进行此转换的方法:

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 belong to the class System.ComponentModel PropertyDescriptor属于类System.ComponentModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM