2011-07-25 22 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