开发者

Best practice for "graphic" if-statments in MVC 3

Just started converting to MVC from classic ASP and wondering about best practice for if-statements that is used to decide if a HTML-element should be visible or deciding if that or that HTML-element should be visible.

Example:

if (type = 1)
{
    <img src="/Content/Images/gray.jpg" />
}
else
{
    <img src="/Content/Images/blue.jpg" />
}

I 开发者_运维技巧see several options here.

1. Use if-statements in my views (prefer not to)

2. Use a HTML-helper (will be a lot of helpers = Hard to work with the code)

3. Create HTML-snippets in my controller and pass into my view

4. Work with JavaScript to show/hide element on document load.

The example above if of course a simplification of my problem. Many thanks for the help!

/Mike

EDIT: Took a bad example, here comes a new:

if (type = 1)
{
    <span class="class1">Something something</span>
}
else
{
    <div id="id1">
        text 
        <img src="/Content/Images/gray.jpg" />
    </div>
}


Personally I'm starting to use a separate layer for loading up by viewmodels with html specific information.

 public class ViewModel
 {
     public string ImageName { get; set; }
 }

Keeps the views clean:

<img src="/Content/Images/<%= Model.ImageName %>.jpg" />


I personally prefer to use HtmlHelper extensions or declarative HTML helpers for all but most trivial conditional expressions. However in this case I would probably let my laziness win, and express the conditional directly in the view like so:

<img src="/Content/Images/@(i == 1 ? "gray" : "blue").jpg" />

Edit

For more complex scenarios, definitely HTML helpers. If you're using the Razor syntax, you can create declarative helpers by placing them into your ~/Views/Helpers directory. They're very clean to write and use.

But the idea behind creating a good helper is that it encapsulates an intention. This is easy to test by trying to give your helper a name. If the name is IfOneThenShowSomethingElseGrayImage, you should try to break it into further pieces still.

So let's imagine the intention in your example is to show information about the current user based on the user type. You could create a helper like this:

@helper UserType(int type) {
   @if (type == 1) {
    <span class="class1">Something something</span>
   } else {
    <div id="id1">
        text 
        <img src="/Content/Images/gray.jpg" />
    </div>
   }    
}

And then use it in your view like this:

@UserType(Model.UserType)

Even though it's only used on one page, it enhances the readability in the view, and can be reused if necessary.

Just my two cents.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜