传递对象到HTML属性 [英] Passing an object to HTML attributes
问题描述
要HTML属性如何传递一个对象?
比如我有以下的code:
How to pass an object to HTML attributes? For example I have the following code:
var attrs = new { id = "myid", style = "color: Red;" };
如何ATTRS转换为字符串,这样它们嵌入到HTML标记:
How to convert attrs to string like this to embed them into an HTML markup:
id="myid" style="color: Red;"
在此先感谢:)
推荐答案
这个功能,令人惊讶的是,由<一个提供href=\"http://msdn.microsoft.com/en-us/library/system.web.routing.routevaluedictionary.aspx\"><$c$c>RouteValueDictionary$c$c>类:
This functionality is, surprisingly enough, provided by the RouteValueDictionary
class:
IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs);
您可以使用这个字典中以<连词href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.tagbuilder.aspx\"><$c$c>TagBuilder$c$c>,这你可能会用反正:
You can then use this dictionary in conjunction with a TagBuilder
, which you will probably be using anyway:
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.ToString(TagRenderMode.Normal);
您可以看到这个在ASP.NET MVC源$ C $ C本身完成;的简单的例子之一是在<一个href=\"https://github.com/mono/aspnetwebstack/blob/1ccfcdfc11da19a88f6efc6f512e67b68fa04fec/src/System.Web.Mvc/Html/TextAreaExtensions.cs#L158-L191\">TextAreaExtensions.cs.
You can see this done in the ASP.NET MVC source code itself; one of the simpler examples is in TextAreaExtensions.cs.
编辑:
为了正确地转换data_attr到数据ATTR,使用 AnonymousObjectToHtmlAttributes
静态方法。
In order to properly convert "data_attr" to "data-attr", use the AnonymousObjectToHtmlAttributes
static method.
IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
这篇关于传递对象到HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!