Tag Helpers in ASP.Net vNext and MVC 6

I've been playing around with the new ASP.Net / MVC 6 in Visual Studio 2015. One notable difference is the new tag-based (razor?) syntax for building views. I've always heavily customised my HTML and AJAX helpers in previous versions of MVC so I thought I'd have a play with the new tag helper. The tag helper allows you to write standard HTML tags, which are then run against the Tag Helpers for which it matches the criteria for. The Tag Helper criteria can be defined by the tag name, as well as more specifically by attributes present.

One thing that I use alot is AJAX. helpers - something which has been omitted from the new version of MVC, so I've written a custom tag helper to allow me to use the previous unobtrusive-ajax library. The old @Ajax.BeginForm helper created data- tags for the library to use, so my tag helper will do something similar:

[TargetElement("form", Attributes = AjaxForm)]
    public class UnobtrusiveFormTagHelper : TagHelper
        private const string AjaxForm = "asp-ajax";

        public string AspOnSuccess { get; set; }

        public bool AspAjax { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
            base.Process(context, output);

            output.Attributes.Add("data-ajax", true);
            output.Attributes.Add("data-onsuccess", AspOnSuccess);



So, the first thing is the Target Element annotation. This means this tag helper will be run against any html form tag, with an attribute of "asp-ajax". You can also see that it accepts an elemet "asp-onsuccess" which I will use the value of to add my data-onsuccess attribute value. I know that I could just have used "data-onsuccess" to start with, however this way I can take advantage of the intellisense. In the example below - because I have added asp-ajax to the tag, I can see the specific asp-onsuccess attribute available in the intellisense list, which is because I have it listed as an html attribute in my helper above:

For anyone else using my custom tag helpers, this now makes for an easy life as they can see exactly which other custom attributes my tag helper is expecting without digging into the code.

One final thought...

When building this helper, I thought that I'd have to handle creating the URL etc. In fact, as the tag still matches the criteria of the built-in form helper (in that it is a <form> tag), that helper also runs on the tag, using asp-action and asp-controller to generate the URL, so no extra work to do there! Also, to bear in mind when the default tag helper behaviour could interfere with your tag helper...


Tagged: MVC, ASP.NET vNext,
Categorised: ASP.NET MVC,