2013-07-17 30 views
1

以下代碼片段有效地表示大型表單中的項目。我的目標是重構它。視圖中的重構控制模式

<div class="span3"> 
<ul style="list-style-type: none"> 
    <li><b>Description</b></li> 
    <li> 
     <textarea style="width: 100%;" rows="4">@Model.Item.Description</textarea> 
    </li> 
</ul> 
</div> 
<div class="span3"> 
<ul style="list-style-type: none"> 
    <li><b>Truck</b></li> 
    <li> 
     @Html.DropDownListFor(model => model.Item.ShippingTruckId, new SelectList(Model.ShippingTrucks, "Id", "Truck")) 
    </li> 
</ul> 
</div> 
<div class="span3"> 
<ul style="list-style-type: none"> 
    <li><b>Cost</b></li> 
    <li> 
     <input value="@Model.Item.Cost"/> 
    </li> 
</ul> 
</div> 

我考慮過的兩種方法是局部視圖和HTML助手。但最終,如何將這一對變成一個更小更容易的區域。我通常要麼有一個輸入,一個文本區域,一個下拉列表,或者在某些情況下是一個標籤。有沒有我想過的另一種優越的方法,或者我提到的一個固有的缺點/優點/挑戰?

回答

2

與反思可以讀取所有屬性和EditorFor創建的元素:

Example for Reflection I
Example for reflection II

有了第一個例子:

@foreach (var property in Model.EnumerateProperties()) 
{ 
    <div class="span3"> 
    <ul style="list-style-type: none"> 
     <li><b>@Html.LabelForProperty(Model,property);</b></li> 
     <li> 
      @Html.EditorForProperty(Model,property); 
     </li> 
    </ul> 
    </div> 
} 

而且herehere你可以看到使用不同類型屬性的編輯器模板或使用UIHint。

編輯該評論::「你如何處理dropdownlists這種方式?」

在這種情況下,我可以想到一個解決方案,但有點複雜。你可以對物業放一個屬性,是這樣的:

[ItPropertyHaveAList("PropertyWithListList")] 
public int PropertyWithListId { get; set; } 

public IEnumerable<SelectListItem> PropertyWithListList { get; set; } 

然後擴展EditorForProperty可以檢測如果屬性具有這個屬性like this example

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] 
public string FirstName {get;set;} 

StringLengthAttribute strLenAttr = 
    typeof(Person).GetProperty("FirstName").GetCustomAttributes(
    typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single(); 


int maxLen = strLenAttr.MaximumLength; 

在這個屬性你從列表中把方法數據創建一個下拉列表。請參閱this迴應,瞭解如何爲下拉列表創建模板。

+0

這是一個夢幻般的答案,並且非常有幫助。 在我接受之前,我有一個問題 - 你如何處理dropdownlists這種方式? – Seth

+0

@親見我的評論 –

相關問題