2011-06-03 43 views
1

我正在使用MVC3瓦/剃刀,我有一個模型,有不少屬性,有時是空的。 除了自定義htmlHelper,或者在視圖中爲每個LabelFor/DisplayFor對使用if/then,是否有一種方法可以不顯示空或空屬性的LabelFor/DisplayFor?不使用LabelFor顯示空屬性的標籤?

回答

1

沒有....你需要上述解決方案或額外的視圖模型。抱歉!

1

我創建了自己的助手:LabelAndDisplayFor來檢查空/空,然後選擇顯示的字段。

public static MvcHtmlString LabelAndDisplayFor<tModel, tValue>(this HtmlHelper<tModel> html, System.Linq.Expressions.Expression<Func<tModel, tValue>> field, 
     bool hideIfEmpty = false) { 

     if (hideIfEmpty) { 
      var v = field.Compile()(html.ViewData.Model); 
      if (v == null || string.IsNullOrWhiteSpace(v.ToString())) { 
       return MvcHtmlString.Empty; 
      } 
     } 

     StringBuilder result = new StringBuilder(); 
     result.Append("<div class='display-line'>"); 
     result.Append("<div class='display-label'>"); 
     result.Append(html.LabelFor(field)); 
     result.Append("</div>"); 

     // ... etc ...