Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if" considered harmful in ASP.NET MVC View (.aspx) files?

I remember seeing a blog (or something) that said you should not use <% if ... %> in .aspx files in ASP.NET MVC, but I can't remember what it said the alternative is. Can anyone remember seeing this and point me to it?

like image 951
JoelFan Avatar asked Jan 11 '10 13:01

JoelFan


2 Answers

Basically what it means is that you shouldn't have huge if statements in your Views, your Controllers and ViewModels should be able to handle the logic. Example:

<h2 class="title">
    <% if (ViewData["category"] == null { %>
        All Products
    <% } else { % >
        <%= ViewData["category"] %>
    <% } %>
</h2>

Should be:

<h2 class="title>
    <%= Model.Title %>
</h2>

If your controllers and ViewModels can't handle the logic, you should write Html Helpers for more complicated logic (thus making it reusable and more readable).

<h2 class="title>
    <%= Html.GetPageTitle(Model.Category) %>
</h2>
like image 167
Martin Avatar answered Oct 19 '22 12:10

Martin


I think what you're referring to is a post by Rob Conery, where he mentions a rule he uses:

If there's an if, make a helper

So to answer your question, the idea is that if you find yourself needing to use if in your View, you should consider adding a helper extension method to render that part of your View instead.

like image 9
Mike Powell Avatar answered Oct 19 '22 12:10

Mike Powell