Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 6 Tag Helpers as Replacement for Editor Templates

MVC 6 introduces Tag Helpers as a better alternative to @Html.EditorFor. It is possible to create custom Editor Template. It's also possible to create a custom Tag Helper.

However, when creating the Tag Helper, the HTML needs to be created by C# code (using TagBuilder, etc.). For complex Tag Helpers it's not as convenient as using a Razor syntax.

Is there any way I'm missing that would allow me to create an custom Tag Helper from a Razor page?

like image 390
Sergey Kandaurov Avatar asked Aug 08 '15 16:08

Sergey Kandaurov


1 Answers

The beauty of TagHelpers 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>
like image 144
N. Taylor Mullen Avatar answered Oct 04 '22 04:10

N. Taylor Mullen