Here’s a simple MVC View that displays all Areas in a DB and then lists all Carreras in each Area under the header.
<h2>Listado General de Carreras</h2>
<% foreach (var Area in (List<string>)ViewData["Areas"])
{ %>
<p><span class="titulo"><%: Area%></span></p>
<% foreach (var carrera in Model)
{
if (carrera.Area.Nombre == Area)
{ %>
<p><%=Html.ActionLink(carrera.Nombre, "Details", new { id = carrera.ID })%></p>
<% }
}
}%>
Do you think you can make this code a bit prettier/efficient?
You could get rid of the
if(crrera.Area.Nombre == Area)with Linq. From the look of it yourModelis some type ofIEnumerableso your inner loop would becomeThis wouldn’t really help with “efficiency” but it is definitely “prettier” IMHO
Couple of MVC 3 features would also help on the prettiness front. First the Razor syntax, and second the new ViewModel property is of type dynamic so you’d get rid of the nasty dictionary lookup on ViewData and its associated cast i.e. your outer loop would become
You could achieve something similar by creating a view specific model and tacking the Areas property on to that model