Blog Stats
  • Posts - 27
  • Articles - 0
  • Comments - 19
  • Trackbacks - 10

 

Thursday, September 04, 2008

ASP.NET MVC - Beautifying Views

This is a simple technique I recently started using to clean up MVC views.

Here was my first attempt at rendering a list of alerts:

<table class="tabTable">
    <tr>
        <th></th><th>VEHICLE</th><th>ALERT TYPE</th><th>WHEN</th><th>ACT</th>
    </tr>
<%
    foreach (FleetAlertDTO alert in ViewData.Model)
    {
%>       
        <%= Html.RenderUserControl("~/Views/Alert/FleetAlert.ascx", alert) %>
<%
    }   
%>
</table>

I didn't like it because there are to many <% %>. Using Response.Write() can help eliminate much of the switching between html and C#. Here is what I ended up with.

<table class="tabTable">
    <tr>
        <th></th><th>VEHICLE</th><th>ALERT TYPE</th><th>WHEN</th><th>ACT</th>
    </tr>
<%
    foreach (FleetAlertDTO alert in ViewData.Model)
    {
        Response.Write(Html.RenderUserControl("~/Views/Alert/FleetAlert.ascx", alert));
    }   
%>
</table>
It's a simple change, but I think it is much more readable.
 

 

Copyright © Liam McLennan