2011-10-05 151 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<>表达式。这样,它不会被绑定到一个模型。