2012-08-07 52 views
1

如何在一行內的複選框中顯示每個屬性 我有對象要素具有許多屬性,這些屬性是動態分配的,我不想在視圖中對這些屬性進行硬編碼。 所以,現在我有一些像這樣的用一行渲染對象屬性

@Html.CheckBoxFor(model => model.Features.IsRegistered, new { @disabled = "disabled" }) 
@Html.CheckBoxFor(model => model.Features.IsPhone, new { @disabled = "disabled" 

....等等

如何呈現酷似以上這些也是所有對象的屬性,這可能嗎? 感謝

回答

0

我只是做這個一些有限的測試,但這裏有一個基本的實現擴展方法,你可以玩:

public static class HtmlHelperExtensions 
{ 
    public static MvcHtmlString CheckBoxesForModel(this HtmlHelper helper, 
     object model) 
    { 
     if (model == null) 
      throw new ArgumentNullException("'model' is null"); 

     return CheckBoxesForModel(helper, model.GetType()); 
    } 

    public static MvcHtmlString CheckBoxesForModel(this HtmlHelper helper, 
     Type modelType) 
    { 
     if (modelType == null) 
      throw new ArgumentNullException("'modelType' is null"); 

     string output = string.Empty; 
     var properties = modelType.GetProperties(BindingFlags.Instance | BindingFlags.Public); 

     foreach (var property in properties) 
      output += helper.CheckBox(property.Name, new { @disabled = "disabled" }); 

     return MvcHtmlString.Create(output); 
    } 
} 

您不妨就擴大到允許其採取HTML屬性,而不是硬編碼它們,但這應該讓你開始。