Dealing with ASP.NET MVC “tag soup”

梦想的初衷 提交于 2019-12-05 13:09:21

I believe your "tag soup" pain is actually a symptom of a different problem: you're feeling it because you've got logic in your view. Views should be very lightweight, with little or no logic. Your logic should be in your controllers, which can decide to render different views depending on the logic. Or you can put the logic into helpers.

See this article by Rob Conery

With proper view model (and optionally, with spark view engine), there is no tag soup.

Particularly, if templates are used.

Can't tell much about this example (even less - to sort it out), but for me - usually it's all about sense of tidiness and ability to structure things properly.


"I'm looking for a code formatting solution." => then you must check out spark. It 'htmlifies' your views even if they do contain logic.

Your example in it (without restructuring anything) =>

<var nullText="ViewData.ModelMetadata.NullDisplayText"
     templateDepth="ViewData.TemplateInfo.TemplateDepth"
     simpleDisplayText="ViewData.ModelMetadata.SimpleDisplayText"
     props="ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))" 
     m="ViewData.Model"/>
<if condition="m==null">
  ${nullText}
</if>
<elseif condition="templateDepth>1">
  ${simpleDisplayText}
</elseif>
<else>
  <for each="var prop in props">
    <if condition="prop.HideSurroundingHtml">
      ${Html.Display(prop.PropertyName)}
    </if>
    <else>
      <span if="!string.IsNullOrEmpty(prop.GetDisplayName()" class="display-field">
        ${prop.GetDisplayName()}
      </span>
      <span class="display-field">
        ${Html.Display(prop.ProperyName)}
      </span>
    </else>
  </for>
</else>

Might be wrong somewhere, but you got the idea.

For our current project, we cleaned up all the if-elses somewhat by writing an HTML helper:

public static void WriteIf(this HtmlHelper helper, bool condition, string truePart, string falsePart)
{
     helper.ViewContext.HttpContext.Response.Write(condition ? truePart : falsePart);
}

and then in the HTML, you would say:

<% Html.WriteIf(Model.IsTrue(), "TrueText", "FalseText"); %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!