In the older MVC HTML Helpers, one could use IDisposable
to wrap content - for example the BeginForm
helper would automatically wrap *stuff*
with a closing form
tag
<% using (Html.BeginForm()) {%>
*stuff*
<% } %>
Is this wrapping of content supported with MVC6 TagHelpers? For example I would like this
<widget-box title="My Title">Yay for content!</widget-box>
to be expanded into a bootstrap widget-box with wrapping divs:
<div class="widget-box">
<div class="widget-header">
<h4 class="widget-title">My Title</h4>
</div>
<div class="widget-body">
<div class="widget-main">
Yay for content!
</div>
</div>
</div>
Is this possible with TagHelpers?
Solution: I have baked @DanielJG's answer into a working demo on github which consumes WidgetBoxTagHelper.cs (will stay current with Beta/RC/RTM as am using the lib in my production app)
Tag helpers have to implement the interface
ITagHelper
(as pointed by @NTaylorMullen, theTagHelper
class is just a convenience class you can use when implementing it) which forces you to use the methodsProcess
andProcessAsync
, so you cannot rely on adding contents in aDispose
method.However you have full control over the output content so you can replace/modify it as you need. For example, a quick approximation to your widget tag helper (Using the 1.0 version of the framework):
In your razor you will have:
Which will be rendered as:
Don´t forget to register the tag helpers in your assembly by adding a
@addTagHelper
directive to the _ViewImports.cshtml file. For example this will register all helpers in my application:OLD beta7 code
[TargetElement]
attribute.SetInnerText
method you could use to set its context as text.The code looked like:
OLD beta5 code
InnerHtml
property in the tag helpers.ToHtmlString
method in the tag helpers used to render them as html.The code looked like: