在asp.net mvc中,我总是看到内置的html助手,他们总是有对象htmlAttirbutes.
然后我经常做新的{@id ="test",@ class ="myClass"}.
如何在我自己的html助手中提取这样的参数?
就像我使用"HtmlTextWriterTag"一样,他是一种可以将整个对象传递给作者的方式,它可以解决它或者什么?
此外,这如何与大html助手一起工作?
就像我正在制作一个html帮助器,它使用所有这些标签.
Table
thead
tfooter
tbody
tr
td
a
img
Run Code Online (Sandbox Code Playgroud)
这是否意味着我必须为每个标签制作一个html属性?
rre*_*ejc 36
我通常做这样的事情:
public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, object htmlAttributes)
{
return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
}
public static string Label(this HtmlHelper htmlHelper, string forName, string labelText,
IDictionary<string, object> htmlAttributes)
{
// Get the id
if (htmlAttributes.ContainsKey("Id"))
{
string id = htmlAttributes["Id"] as string;
}
TagBuilder tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("for", forName, true);
tagBuilder.SetInnerText(labelText);
return tagBuilder.ToString();
}
Run Code Online (Sandbox Code Playgroud)
我建议你从codeplex下载ASP.NET MVC源代码,看看内置的html帮助器.
您可以将对象htmlAttirbutes转换为这样的属性/值字符串表示形式:
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('_', '-'), HttpUtility.HtmlAttributeEncode(property.GetValue(htmlAttributes).ToString()));
}
Run Code Online (Sandbox Code Playgroud)
PropertyDescriptor
属于阶级 System.ComponentModel
归档时间: |
|
查看次数: |
11731 次 |
最近记录: |