Sunday, April 17, 2011

Conditionals in Views

I am fairly new to ASP MVC and was wondering what is the best way to handle conditional statements in your views? I am sure there isn't a one size fits all approach, but for simple checks is it wise to have If-Then-Else statements littering the view?

For example, say I have a list and wish to set the class on one of the list items if one of the model properties is set.

<% if (myModel.MyProperty == 1) { %>
   <li class="myClass">
<% } else { %>
   <li>
<% } %>

Is this the best way to approach this, or is there a better way? I am just concerned that if you have numerous conditionals like this in your view it is going to start to look pretty messy.

Thanks in advance for any advice.

From stackoverflow
  • I would put this in your controller. Assuming you don't mind having

    <li class="">
    
    Ash : I would _not_ put this in the controller. Setting things like css classes is display logic and doesn't belong in the controller. Keep it in the view I say.
  • <ul>
        <% foreach (var item in Model.Items) { <%
        <li<%= item.HasProperty ? " class="\class\"" : "" %>>
            <%= Html.Encode(item.Name) %>
        </li>
        <% } %>
    </ul>
    
    Jon Archway : That works well. Now, let's say you have a list of 10 items (or even more) if you used the method you mention above you will have that conditional in every single list item. For list item 1 if model.property ==1 then set class, if item 2 has property of 2, etc. Isn't thid going to be a little messy?
    Koistya Navin : with repitive items you probably will use loops with one li element
  • If you really want a cleaner view, you could create a helper:

    public static class MyHelpers {
        // Need a more descriptive name (based on what you're generating)
        public static string MyListItemHelper(this HtmlHelper helper, bool condition) {
            if(condition) {
                return "<li class=\"myClass\">";
            } else {
                return "<li>";
            }
        }
    }
    

    Then your view is just:

    <%= Html.MyListItemHelper(myModel.MyProperty == 1) %>
        ...
    </li>
    

0 comments:

Post a Comment