Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is conditional logic in an MVC3 view a good practice?

Here's an example view, I use it to output every Category in my database. It's a recursive relationship, so a Category can have a List<Category> of Subcategories.

@model DSS.WebUI.Models.CategoriaModel

<div class="categories">
    <h3>
        @if (Model.Subcategorias.Count > 0)
        {
            <img src="http://i.imgur.com/t5UXT.gif" />   
            <a href="#">@Model.Nombre</a>
            <p class="subtext">@Model.Encabezado</p>
        }
        else
        {
            <a class="nochild" href="#">@Model.Nombre</a>
            <p class="subtext nochild">@Model.Encabezado</p>
        }
    </h3>
    <div>
        <ul>
            @Html.DisplayFor(x => x.Subcategorias)
        </ul>
    </div>    
</div>

Is conditional logic like this kosher? Or is it a code smell I should avoid and how?

like image 513
Only Bolivian Here Avatar asked Dec 31 '25 16:12

Only Bolivian Here


2 Answers

This kind of conditional logic looks fine to me. Based on the number of sub-categories you have in your view model you are generating one or another html fragment. What would have been bad is to repeat this exact same condition with the same output in many places of your application. In this case you could externalize it into a partial or write a custom HTML helper.

like image 81
Darin Dimitrov Avatar answered Jan 02 '26 04:01

Darin Dimitrov


I think it's better to implement your logic inside your controller instead of HTML codes, in these situation I try to do something like following :

    @if (ViewBag.SubCategoryHasData)
    {
        <img src="http://i.imgur.com/t5UXT.gif" />   
        <a href="#">@Model.Nombre</a>
        <p class="subtext">@Model.Encabezado</p>
    }
    else
    {
        <a class="nochild" href="#">@Model.Nombre</a>
        <p class="subtext nochild">@Model.Encabezado</p>
    }

and inside your action :

    ViewBag.SubCategoryHasData = Subcategorias.Count > 0;

hope this help.

like image 31
saber Avatar answered Jan 02 '26 05:01

saber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!