2010-02-10 102 views
1

我繼承下面的代碼,我想知道如果我能在你的大腦挑來看看有沒有做重複這個更好的方式。需要幫助想出一個更好的HtmlHelper擴展方法

繼承人我們大多數部分輸入的HTML視圖

<% if (Html.IsInputReadOnly()) { %> 
<td> 
    Id 
</td> 
<td> 
<%= Html.TextBox(
    "Id" 
    , (Model == null ? null : Model.Id) 
    , new { @readonly = "readonly", @disabled="disabled" } 
)%> 
<% } elseif (Html.IsInputDisplayable() == false) { %> 
<td></td> 
<td></td> 
<% } else { %> 
<td>Id</td> 
<td><%= Html.TextBox("Id")%> 
    <%= Html.ValidationMessage("Id", "*")%> 
</td> 
<%} %> 

這裏是我的entension方法

public static bool IsInputReadOnly(this HtmlHelper helper) 
{ 
    string actionName = ActionName(helper); 

    // The Textbox should be read only on all pages except for the lookup page 
    if (actionName.ToUpper().CompareTo("EDIT") == 0) 
     return true; 
    return false; 
} 

public static bool IsInputDisplayable(this HtmlHelper helper) 
{ 
    string actionName = ActionName(helper); 

    // The Textbox should be read only on all pages except for the lookup page 
    if (actionName.ToUpper().CompareTo("CREATE") == 0) 
     return true; 
    return false; 
} 

在此先感謝

回答

0

我會分離出只讀和可編輯部分分成2個單獨的部分視圖。留給你的控制器來決定應該渲染哪個視圖。你不應該在你的意見來做出這些種類的決定 - 他們應該是愚蠢的。

+0

我同意的意見必須是愚蠢的,但在什麼的情況下,「控制x應爲條件1被啓用,但是對於條件2禁用」的情況的?所以,我給這個問題+1。 – Sunny 2010-02-10 18:04:13

0

如果你能創造出具有鍵值對,其中鍵=控件名稱&值= HtmlAttributes該控件集合的對自定義視圖模型類,控制器可能能夠設置這些屬性。

在視圖中,您將直接綁定HtmlAttribute來控制。

有沒有嘗試過了,但可能工作...

HTH

編輯:鍵值對HtmlAttributes可能會像IsEditable,可見性等標誌,可以在視圖中解釋的集合通過擴展方法需要渲染HtmlAttributes讓我們沒有HTML部分混入控制器

1

你可以用所有的邏輯到一個單一的擴展方法?

<%= Html.SmartDisplay("Id", (Model == null ? null : Model.Id))%> 

然後在擴展方法中,放置所有檢查其是可顯示還是隻讀的代碼。如果你沒有在所有網頁上的所有控件的標準表格佈局這將無法正常工作,但如果你這樣做,它可能工作。