Asp.net Vnext TagHelpers

概述


 本文已经同步到《Asp.net Vnext 系列教程 》中]

TagHelpers vnext引入功能之一TagHelper 的作用类似发挥以前版本 ASP.NET MVC  HtmlHelpers

这是HtmlHelpers实现连接

@Html.ActionLink("About Me", "About", "Home", null, new { @class="btn btn-primary" })

这是TagHelper实现连接

<a asp-controller="Home" asp-action="About" class="btn btn-primary">About Me</a>

TagHelper 更像是html

详细介绍:http://www.cnblogs.com/TomXu/p/4496480.html

代码实现


 

 

   /// <summary>
    /// pager  是Tag名称
    /// total-pages,current-page, link-url 是Tag属性
    /// </summary>
    [TargetElement("pager", Attributes = "total-pages, current-page, link-url")]
    public class PagerTagHelper : TagHelper
        {
        public override void Process(TagHelperContext context, TagHelperOutput output)
            {
            int totalPages, currentPage;
            //获取属性值
            if (int.TryParse(context.AllAttributes["total-pages"].ToString(), out totalPages) &&
               int.TryParse(context.AllAttributes["current-page"].ToString(), out currentPage))
                {
                //获取属性值
                var url = context.AllAttributes["link-url"];
                //元素名称
                output.TagName = "div";
                //设置类容
                output.PreContent.SetContent("<ul class=\"link-list\">");

                var items = new StringBuilder();
                for (var i = 1; i <= totalPages; i++)
                    {
                    //用于创建HTML元素
                    var li = new TagBuilder("li");
                    //用于创建HTML元素
                    var a = new TagBuilder("a");
                    // 设置元素属性和值
                    a.MergeAttribute("href", $"{url}?page={i}");
                    a.MergeAttribute("title", $"Click to go to page {i}");
                    a.InnerHtml = i.ToString();
                    if (i == currentPage)
                        {
                        a.AddCssClass("active");
                        }
                    li.InnerHtml = a.ToString();
                    items.AppendLine(li.ToString());
                    }
                output.Content.SetContent(items.ToString());
                output.PostContent.SetContent("</ul>");
                output.Attributes.Clear();
                //   // 设置元素属性和值
                output.Attributes.Add("class", "pager");
                }
            }
        }

 

在视图中_GlobalImport.cshtml 加入TagHelpers 

 

 

@using WebApplication1
@using WebApplication1.Models
@using Microsoft.Framework.OptionsModel
@using Microsoft.AspNet.Identity
@addTagHelper "WebApplication1.PagerTagHelper, WebApplication1"
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"//添加  TagHelpers
@tagHelperPrefix "mb-" //添加前缀名
@addTagHelper  "Microsoft.AspNet.Mvc.TagHelpers.AnchorTagHelper, Microsoft.AspNet.Mvc.TagHelpers" //移除TagHelpers

 

使用

 

运行

 

posted @ 2015-07-04 15:16  欢呼雀跃  阅读(464)  评论(0编辑  收藏  举报