How to create custom tag assistants for razors?

I am trying to create a special tag helper in MVC 6 but cannot make it work.

Here is my helper class for the demo tag defined in a web application project.

namespace Microsoft.AspNet.Mvc.TagHelpers { [TargetElement("demo", Attributes = CustomAttributeName)] public class DemoTagHelper : TagHelper { private const string CustomAttributeName = "asp-custom"; [HtmlAttributeName(CustomAttributeName)] public string Custom { get; set; } public string Value { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; output.Attributes["foo"] = "bar"; } } } 

Here's how I use it in my views:

 <demo asp-custom="hello world!"> Please work this time :) </demo> 

I've tried a lot. TargetElement attribute TargetElement or namespace changed. Nothing changes ... The result is still the same.

By the way, my version of Microsoft.AspNet.Mvc.TagHelpers is 6.0.0-beta4 .

Maybe I need to register my tag helper somewhere? I looked at the MVC source codes and they never referenced their own tag helpers anywhere. Therefore, I think registration is not required.

Where is the problem?

+7
c # asp.net-mvc asp.net-core-mvc tag-helpers
source share
2 answers

You can enable TagHelper processing for custom tags by adding the addTagHelper directive to the addTagHelper file found in the views directory:

 @addTagHelper "*, YourMvcAssembly" 

Update

@yilmaz also needs to add a link to Microsoft.AspNet.Tooling.Razor , as described in the comments below.

+6
source share

This is what I have for the special tag helper now, and it works. I modified it to customize the demo element. Try:

 namespace TestingTagHelpers.TagHelpers { using Microsoft.AspNet.Razor.Runtime.TagHelpers; using System; /// <summary> /// <see cref="ITagHelper"/> implementation targeting &lt;demo&gt; elements. /// </summary> //[TargetElement("demo")] public class DemoTagHelper : TagHelper { public override void Process(TagHelperContext context, TagHelperOutput output) { var childContent = context.GetChildContentAsync().Result; string demoContent = childContent.GetContent(); string demo = context.AllAttributes["asp-custom"].ToString(); output.TagName = "div"; output.Attributes.Clear(); output.Attributes["data-custom"] = demo; output.Content.SetContent(demoContent); } } } 
+2
source share

All Articles