The beauty of TagHelper
s is that you can intermingle C# and Razor in many different ways. So lets say you have a custom Razor template such as:
CustomTagHelperTemplate.cshtml
@model User
<p>User name: @Model.Name</p>
<p>User id: @Model.Id</p>
And you have the model:
namespace WebApplication1
{
public class User
{
public string Name { get; set; }
public int Id { get; set; }
}
}
And the TagHelper
:
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.Framework.WebEncoders;
namespace WebApplication1
{
public class UserTagHelper : TagHelper
{
private readonly HtmlHelper _htmlHelper;
private readonly IHtmlEncoder _htmlEncoder;
public UserTagHelper(IHtmlHelper htmlHelper, IHtmlEncoder htmlEncoder)
{
_htmlHelper = htmlHelper as HtmlHelper;
_htmlEncoder = htmlEncoder;
}
[ViewContext]
public ViewContext ViewContext
{
set
{
_htmlHelper.Contextualize(value);
}
}
public string Name { get; set; }
public int Id { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = null;
output.SelfClosing = false;
var partial = await _htmlHelper.PartialAsync(
"CustomTagHelperTemplate",
new User
{
Name = Name,
Id = Id
});
var writer = new StringWriter();
partial.WriteTo(writer, _htmlEncoder);
output.Content.SetContent(writer.ToString());
}
}
}
You can then write the following page:
@addTagHelper "*, WebApplication1"
<user id="1234" name="John Doe" />
Which generates:
<p>User name: John Doe</p>
<p>User id: 1234</p>