【发布时间】:2011-01-15 23:12:25
【问题描述】:
我今天在做一个 ASP.NET MVC 模板,在盯着所有那些荧光黄色的% 标签足够长之后,我基本上认为我受够了,所以我煞费苦心地将我的 ascx 文件修改为如下所示:
<%@ 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>
<% } %>
<% } %>
<% } %>
啊,终于可读了。唯一的问题是,手动执行此操作需要方式。我需要一种方法来自动化它。某种代码格式化解决方案。也许是宏或 Visual Studio 加载项或...?你有什么建议?
更新
我现在计划从我的标记中重构出大部分逻辑(请参阅下面 Mike 的回答),但与此同时,我想出了一种更易于管理的方式来格式化混合了代码和代码的 ascx 文件html。代码以这种方式分散了一些,但首先像这样格式化代码要容易得多,而且使用起来也容易得多。
<%@ 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>
<%
}
}
}
%>
【问题讨论】:
-
@Kirk,是代码还是格式?
-
哦:哦,你有没有在编码器中维护这个!?呵呵呵呵:P
标签: c# asp.net-mvc visual-studio markup code-formatting