2

I want to stay DRY and therefore need to reuse medium-sized HTML blocks. These blocks are not small enough for me to rely on custom Html helpers (in cs files), yet they are too numerous and not large enough to warrant partial views.

For example, consider a hypothetical block "Feature", which when simplified can look like this:

<div class="feature bg-@Color">
  <h2>@Title</h2>
  <div>[extra-styling of what's under the header]</div>
  <div class="feature-content">[actual HTML content]</div>
</div>

For such a small thing a PartialView seems excessive - there may be up to 100 (or maybe even more) of these on a page (and this is just one kind of an html block - there will be others too).

On the other hand:

  • Writing Html helper is not good, because the HTML structure is complex and putting it into the .cs file seems just wrong.
  • Writing @helper in the App_code folder is not viable either because, while it does allow one to easily see html markup, parameters present a problem, in particular actual HTML content.

The biggest difficulty is that these "blocks" need to be parametrized. In the example above there are 3:

  • 2 small ones: @Title, @Color (both can be easily passed as some .NET primitive type)
  • 1 complex: actual hard-coded HTML content (which itself can have dynamically generated @variables)

So, ideally I need some kind of way to be able to:

  • Create my markup in HTML (not cs code-behind)
  • Be able to pass in simple parameters: color, title, some booleans (which may change rendering)
  • Be able to "pass" somehow one or more HTML contents, around which this template / blocked will be wrapped.

So, in ASP.NET MVC 5, what would be the best approach to achieve this? Or at least, if it's not possible to meet all these requirements, then what would be the easiest way to achieve most of them, staying as DRY as possible?

Fit Dev
  • 3,413
  • 3
  • 30
  • 54
  • What's wrong with HTML helpers? I suggest you look at the source for the `BeginForm` helper, which allows you to pass content to it. Also, for more advanced scenarios, you can make [templated HTML helpers](http://devproconnections.com/development/work-aspnet-mvc-templated-html-helpers) that have the same view model, but different markup. Or, you could go with MVC core and use [view components](https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components) instead. – NightOwl888 Feb 13 '17 at 09:09
  • 1
    You can use @Html.Action helper to let your partial views caught by a controller, this enables you also to cache partial views, and to load a specific model related to your parameters. – Laurent Lequenne Feb 13 '17 at 10:22
  • Possible duplicate of [Creating reusable HTML view components using Razor in ASP.NET MVC](https://stackoverflow.com/questions/23518499/creating-reusable-html-view-components-using-razor-in-asp-net-mvc) – gbjbaanb May 17 '18 at 19:31

0 Answers0