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)
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
以下是如何进行此转换:
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
| 归档时间: |
|
| 查看次数: |
55126 次 |
| 最近记录: |