Custom tag helper -MyEmailTagHelper

 1. In the project which marks a new helper, input MyEmailTagHelper

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyRazor.Models
{
    [HtmlTargetElement("email")]
    public class MyEmailTagHelper:TagHelper
    {

        public string To { get; set; }
        public string Subject { get; set; }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {

            // Evaluate the Razor content of the email's element body 
            var body = (await output.GetChildContentAsync()).GetContent();
            body = body.Trim();

            // Replace <email> with <a> 
            output.TagName = "a";

            // Prepare mailto URL
            var to = context.AllAttributes["to"].Value.ToString();
            var subject = context.AllAttributes["subject"].Value.ToString();
            var mailto = "mailto:" + to;
            if (!string.IsNullOrWhiteSpace(subject))
                mailto = string.Format("{0}&subject={1}&body={2}", mailto, subject, body);

            // Prepare output
            output.Attributes.Remove(context.AllAttributes["to"]);
            output.Attributes.Remove(context.AllAttributes["subject"]);
            output.Attributes.SetAttribute("href", mailto);
            output.Content.Clear();
            output.Content.AppendFormat("Email {0}", to);
        }
    }
}

2. Add @addTagHelper in ViewImports inside *, MyRazor, pay attention to where the second parameter is the assembly name rather than a namespace

@using MyRazor
@using MyRazor.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyRazor

3. The increase in the index view email tag inside, considered normal input process prompted

@model MyRazor.Models.RoomViewModel

@{
    ViewData["Title"] = "Home Page";
}

@{
     var email = "[email protected]";
    var subject = "Hello";
}



<email to="@email" subject="@subject" class="btn btn-danger">
    Hello! Today is @DateTime.Today
</email>



 

 

Published 496 original articles · won praise 76 · Views 300,000 +

Guess you like

Origin blog.csdn.net/dxm809/article/details/104812434