C# 将对象传递给HTML属性
如何将对象传递给HTML属性? 例如,我有以下代码:C# 将对象传递给HTML属性,c#,asp.net,html,asp.net-mvc-3,C#,Asp.net,Html,Asp.net Mvc 3,如何将对象传递给HTML属性? 例如,我有以下代码: var attrs = new { id = "myid", style = "color: Red;" }; 如何将属性转换为如下字符串以将其嵌入HTML标记: id="myid" style="color: Red;" 提前感谢:)您不需要转换为字符串。HTML帮助程序的最后一个参数是对象。 您只需像上面所写的那样给它对象: 例如 @Html.TextBoxFor(x => x.Foo, new { size = 10, max
var attrs = new { id = "myid", style = "color: Red;" };
如何将属性转换为如下字符串以将其嵌入HTML标记:
id="myid" style="color: Red;"
提前感谢:)您不需要转换为字符串。HTML帮助程序的最后一个参数是对象。 您只需像上面所写的那样给它对象: 例如
@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。令人惊讶的是,该功能由类提供: 您可以在ASP.NET MVC源代码中看到这一点;其中一个简单的例子是 编辑: 为了正确地将“数据属性”转换为“数据属性”,请使用
匿名objecttohtmlattributes
静态方法
IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
IDictionary HtmlatAttributes=HtmlHelper.AnonymousObjectToHtmlatAttributes(属性);
以下是如何进行此转换:
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
我知道,但是另外,我想写我自己的方法来呈现另一个表单组件,所以我需要一种类似MVC 3的方法:)np你可能应该在你的问题中提到这一点谢谢你的问题!我救了我的一天!只需使用属性data_bind进行尝试,结果是data_bind,而不是预期的数据绑定-有什么想法吗?不幸的是,TextAreaExtensions的Url不再有效:)只是让您知道。还有一个替代方法,System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlatAttributes(),这可能更合适;它以与标准MVC Html帮助程序相同的方式将下划线替换为连字符。此答案已过时。正确的方法应该是HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)
这将正确处理数据_blah
类型属性。不知道为什么这不是建议的答案。代码没有问题,但有一个重要的更改:使用HttpUtility.htmlAttributeNCode呈现属性值。还可以在x-y中转换标记名x_y。TagBuilder就是这样做的。
IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
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));
}