自定义标记帮助程序-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>



 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值