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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With