In Razor, there's a curious rule about only allowing closed HTML within an if
block.
See:
Razor doesn't understand unclosed html tags
But I have a situation where I want to exclude some outer, wrapping elements under certain conditions. I don't want to repeat all the inner HTML, which is a fair amount of HTML and logic.
Is the only way around the problem to make yet another partial view for the inner stuff to keep it DRY?
Without any other re-use for this new partial, it feels really awkward, bloaty. I wonder if the rule is a limitation of Razor or simply a nannying (annoying) feature.
You can use
Html.Raw(mystring)
. InmyString
you can write whatever you want, for example a tag opening or closing, without getting any errors at all. I.e.NOTE: the
@Html.Raw("<div>")
can be written in a shorter, alternative form, like this:@:<div>
You can also create your own html helpers for simplifying the razor syntax. These helpers could receive the condition parameter, so that you can do something like this:
or more complicated helpers that allow to specify attributes, tag name, and so on.
Nor the
Raw
, neither the html helpers will be detected as "tags" so you can use them freely.The Best Way to do it
It would be much safer to implement something like the
BeginForm
html helper. You can look at the source code. It's easy to implement: you simply have to write the opening tag in the constructor, and the closing tag in theDispose
method. The adavantage of this technique is that you will not forget to close a conditionally opened tag.You need to implement this html helper (an extension method declared in a static class):
Which uses a class like this:
You can use this with the same pattern as
BeginForm
. (Disclaimer: this code is not fully tested, but gives an idea of how it works. You can accept extra parameters for attributes, tag names and so on).