2011-10-05 153 views
0

如果我想多如果在HTML語句屬性我可能會做這樣的事情:多 - MVC剃刀

<input type="button" value="Bad, the title has a lot of excess spacing" title="@if(SomeModel.condOne) { 
           <text>this</text> 
           } 
           @if (SomeModel.CondTwo) 
           { 
           <text> is</text> 
           } 
           @if (SomeModel.CondThree) 
           { 
           <text> a title</text> 
           }  
          " /> 

但是,這創造了很多需要截斷空的空間。所以這個工程:

<input type="button" value="Good, the title is condenced" title="@if(SomeModel.condOne) {<text>this</text>}@if (SomeModel.CondTwo){<text> is</text>}@if (SomeModel.CondThree){<text> a title</text>}" /> 

同樣的原則也適用於多類元素(如類=「oddrow class1的」 - >類=「evenrow類class2」)

但是,這可能很難閱讀是否很長。並且,如果您觸摸括號或Ctrl-K,Ctrl-D(任何下一個開發人員可能會這樣做),Visual Studio都有將此語句分成多行的習慣。

是否有更好或更全面的方式來實現MVC剃刀一行中的多個屬性條件?

回答

0

我建議創建一個小助手方法來返回你需要的文本。

你必須通過它SomeModel並在該方法內檢查你的條件,這樣你會有更好的東西看,更容易維護。

例如:

public static class HtmlHelpers 
{ 
    public static string FetchTitle(this HtmlHelper helper, SomeModel model) 
    { 
     //Your logic here. 
    } 
} 

你可以閱讀所有關於這裏Jon Galloway's blog HTML輔助方法。

這就是我學會如何使用它們的地方。

0

爲什麼不這樣做的:

title="@if(SomeModel.condOne) { <text>this</text> } 
     @if (SomeModel.CondTwo) { <text> is</text> } 
     @if (SomeModel.CondThree) { <text> a title</text> }  
          " /> 

助手有道理的,如果你使用這個相同的邏輯很多,特別是假設同一型號,但您可能還希望考慮使用一個Func<>表達幫手或Action<>表達式。這樣,它不會被綁定到一個模型。