2011-07-25 20 views

回答

2

无需使用的HtmlHelper功能时时处处,如果他们不适合你的需求。他们只是想让你的生活更轻松,而不是更难。在这里使用优秀的HTML:

<label id="id_for_label"></label> 
+0

它是不是需要可见的属性,不工作! – michael

0

如果你想继续使用HtmlHelper函数,你总是可以创建自己的扩展方法。

例如:

public static class LabelHelper 
{ 
    private static string HtmlAttributes(object htmlAttributes) 
    { 
     var builder = new StringBuilder(); 
     foreach (PropertyDescriptor descriptor in 
      TypeDescriptor.GetProperties(htmlAttributes)) 
     { 
      builder.AppendFormat(" {0}=\"{1}\" ", descriptor.Name, 
       descriptor.GetValue(htmlAttributes)); 
     } 
     return builder.ToString(); 
    } 

    public static MvcHtmlString MyLabel(this HtmlHelper htmlHelper, 
     string labelText, object htmlAttributes) 
    { 
     var attributes = HtmlAttributes(htmlAttributes); 
     return MvcHtmlString.Create(
      String.Format("<label for=\"{0}\" {1}>{0}</label", 
      labelText, attributes.Trim())); 
    } 
} 

然后,可以以下面的方式将标签添加至的视图:

<%: Html.MyLabel("Hello, World!", new { @id = "myLabel" })%> 

生成的HTML是:

<label for="Hello, World!" id="myLabel">Hello, World!</label> 

对于MVC 3这样的辅助功能已经可用:

http://msdn.microsoft.com/en-us/library/gg538318(v=VS.99).aspx