I was working on an ASP.NET MVC template today, and after staring at all those fluorescent yellow %
tags for long enough, I basically decided I had had enough, so I painstakingly modified my ascx file to look like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% if (Model == null)
{ %>
<%= ViewData.ModelMetadata.NullDisplayText %>
<% }
else if (ViewData.TemplateInfo.TemplateDepth > 1)
{ %>
<%= ViewData.ModelMetadata.SimpleDisplayText %>
<% }
else
{ %>
<% foreach (var prop in ViewData.ModelMetadata.Properties.Where(
pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
{ %>
<% if (prop.HideSurroundingHtml)
{ %>
<%= Html.Display(prop.PropertyName) %>
<% }
else
{ %>
<% if (!String.IsNullOrEmpty(prop.GetDisplayName()))
{ %>
<span class="display-label">
<%= prop.GetDisplayName() %>
</span>
<% } %>
<span class="display-field">
<%= Html.Display(prop.PropertyName) %>
</span>
<% } %>
<% } %>
<% } %>
Ahh readability at last. The only problem is, it takes way to long to do this by hand. I need a way to automate this. Some kind of code formatting solution. Perhaps a macro or a Visual Studio add-in or ...? What do you advise?
Update
I'm now planning to refactor out most of the logic from my markup (see Mike's answer below), but in the mean time, I came up with a more manageable way to format ascx files that have a mixture of code and html. The code is a little more spread out this way, but it's much easier to format the code like this in the first place, and it's much easier to work with as well.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
if (Model == null)
{
%>
<%= ViewData.ModelMetadata.NullDisplayText %>
<%
}
else if (ViewData.TemplateInfo.TemplateDepth > 1)
{
%>
<%= ViewData.ModelMetadata.SimpleDisplayText %>
<%
}
else
{
%>
<%
foreach (var prop in ViewData.ModelMetadata.Properties.Where(
pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
{
if (prop.HideSurroundingHtml)
{
%>
<%= Html.Display(prop.PropertyName) %>
<%
}
else
{
%>
<div class="display-row">
<%
if (!String.IsNullOrEmpty(prop.GetDisplayName()))
{
%>
<div class="display-label">
<%= prop.GetDisplayName() %>
</div>
<%
}
%>
<div class="display-field">
<%= Html.Display(prop.PropertyName) %>
</div>
</div>
<%
}
}
}
%>