自定义标记帮助程序-MyEmailTagHelper
作者:互联网
1.在项目里面新建标记帮助程序,输入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.在ViewImports里面添加@addTagHelper *, MyRazor,注意这里第二个参数是assembly name而不是命名空间
@using MyRazor
@using MyRazor.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyRazor
3.在index视图里面增加email标签,输入过程有提示才算正常
@model MyRazor.Models.RoomViewModel
@{
ViewData["Title"] = "Home Page";
}
@{
var email = "abc@163.com";
var subject = "Hello";
}
<email to="@email" subject="@subject" class="btn btn-danger">
Hello! Today is @DateTime.Today
</email>
标签:body,mailto,自定义,标记,MyEmailTagHelper,using,output,MyRazor,subject 来源: https://blog.csdn.net/dxm809/article/details/104812434