Tag Archives: razor

TagHelpers : using the post method with html anchor tags

Standard

Want to make an anchor which would issue a post call to the server rather than a get ?

post anchor tag

instead of writing the ugly :

<form asp-controller="Account" asp-action="Logout" method="post" id="logout-form"></form>

 <a href="javascript:document.getElementById('logout-form').submit()"></a>

Why not use a tag helper to generate this behind the scenes and keep your html clean ? Here’s mine, I made it simple, your anchor must have an id, a href and a asp-post attribute to work with it.

    [HtmlTargetElement("a", Attributes = ForAttributeName + ",id,href")]
    public class PostAnchorTagHelper : TagHelper
    {
        private const string ForAttributeName = "asp-post";
        private IHtmlGenerator _generator;

        public PostAnchorTagHelper(IHtmlGenerator generator)
        {
            _generator = generator;
        }

        [HtmlAttributeName(ForAttributeName)]
        public string For { get; set; }

        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }

        public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var href = context.AllAttributes["href"].Value.ToString();
            var id = context.AllAttributes["id"].Value.ToString();
            output.Attributes.RemoveAll("href");
            var form = new TagBuilder("form");
            form.Attributes.Add("action", href);
            form.Attributes.Add("method", "post");
            form.Attributes.Add("asp-antiforgery", "true");
            var idForm = id + "-form";
            form.Attributes.Add("id", idForm);
            var antiforgeryTag = _generator.GenerateAntiforgery(ViewContext);
            if (antiforgeryTag != null)
            {
                form.InnerHtml.AppendHtml(antiforgeryTag);
            }
            output.Attributes.Add("href", $"javascript:document.getElementById('{idForm}').submit()");
            output.PostElement.AppendHtml(form);
            return base.ProcessAsync(context, output);
        }
    }

Now, just write :

<a id="logout" href="@Url.Action("Logout", "Account")" asp-post="true"></a>

And you’re good to go !