How can I draw this repeating pattern in ASP.NET MVC 5?

In my templates, I have repeating blocks of content that I want to reduce to a single component:

<header class="Component-header">
  <!-- Some content here is always the same -->
  <!-- And some content is different for each use -->
</header>
<div class="Component-body">
  <!-- Some content here is always the same -->
  <!-- And some content is different for each use -->
</div>
<footer class="Component-footer">
  <!-- Some content here is always the same -->
  <!-- And some content is different for each use -->
</footer>

Usually for this I would use a partial view of the razor and pass some variables to it. However, in this case, this would mean passing large html fragments as variables, which does not seem wise.

I found this article: http://www.growingwiththeweb.com/2012/09/custom-helper-for-surrounding-block-in.html , which explains how to create block helpers. This is a little closer to what I'm trying to do, but I still need to define html as a string that is not what I want (since the amount of html is large enough to make it unbearable).

, , , . : , , html ?

+4
1

@helper. App_Code, YourComponentName.cshtml. :

@using System.Web.Mvc;

@helper Render(
  ViewContext context,
  string title = "Default title",
  Func<object, object> header = null,
  Func<object, object> content = null,
  Func<object, object> footer = null
)
{
  <header class="Component-header">
    <!-- Some content here is always the same -->
    <h3>@title</h3>
    @if (header != null) { @header.DynamicInvoke(context); }
  </header>
  <div class="Component-content">
    <!-- Some content here is always the same -->
    @if (content != null) { @content.DynamicInvoke(context); }
  </div>
  <footer class="Component-footer">
    <!-- Some content here is always the same -->
    @if (footer != null) { @footer.DynamicInvoke(context); }
  </footer>
}

:

  @YourComponentName.Render(
    ViewContext,
    title: "Title",
    header: @<p>Markup for the header</p>,
    content: @<p>The content</p>,
    footer: @<p>Markup for the footer</p>
  )
+1

All Articles