当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core新特性之TagHelper标签助手

asp.net core新特性之TagHelper标签助手

2017年12月08日  | 移动技术网IT编程  | 我要评论

功夫派碧露丸,剑撼山河,导航电子狗一体机

今天开始,我就来说说asp.net core的新特性,今天就说说taghelper标签助手。虽然学习.net,最有帮助的就是microsoft的官方说明文档了,里面把一些使用说明都写的非常清楚,但奈何.net core放入文档微软还没来得及翻译,对于英文不好的人来说简直就是看的艰辛。所以今天就来学习学习这标签助手,和博客园大佬分享分享经验。

  想看microsoft官方文档和git项目的可以直接点击以下传送门~~

  

  

  说起taghelper给我的印象,有点像asp.net form当中的服务器端控件,又有点像angular或者vue当中的“组件”的后端实现版本。用户可以将一组html标签集合转换为一个自定义标签,实现了html代码的复用。

  那么正文开始~~

  首先,我们需要安装一个vs2017插件:razor language services。这个插件能在html中智能提示用户自定义的标签助手。

  https://marketplace.visualstudio.com/items?itemname=ms-madsk.razorlanguageservices

创建一个asp.net core项目

使用微软定义的标签助手,在安装了插件后,使用标签助手的标签会进行高亮显示

上图中environment、link、a标签均使用了标签助手实现各自的功能

<a asp-area="" asp-controller="home" asp-action="index" class="navbar-brand">taghelpersample</a>

a标签中通过使用asp-controller,asp-action自定义属性来实现路由访问。

这时有人会说,我也可以使用@html类来实现相同功能,为什么需要使用taghelper?

@html.actionlink("taghelpersample", "index", "home",null, new { class = "navbar-brand" })

确实,使用@html帮助类我们能实现相同的功能,但是使用标签助手的方式不是更加符合html的标签语法吗,对于强迫症程序员简直就是福音~~。而且对于标签的原有属性的添加例如class,标签助手的使用也更加方便。

<!--标签助手版form-->
<form asp-controller="home" asp-action="index" class="form-horizontal" method="post">

</form>
<!--html帮助类版form-->
@using (html.beginform("index", "home", formmethod.post,, new { class = "form-horizontal" }))
{

}


此外,标签助手的另外一个特色就是可以自定义,具体步骤如下:

(1)创建派生自taghelper类的class

 //类会默认转换为<text-collection></text-collection>
   public class textcollectiontaghelper:taghelper
 {
  public override void process(taghelpercontext context, taghelperoutput output)
  {
   base.process(context, output);
  }
 }


(2)设置属性与基本类

public string color { get; set; }

  public override void process(taghelpercontext context, taghelperoutput output)
  {
   output.tagname = "div";
   output.attributes.add("style", "color:" + color);
   var text = "hello,world";
   var h1 = new tagbuilder("h1");
   var h2 = new tagbuilder("h2");
   var h3 = new tagbuilder("h3");
   var h4 = new tagbuilder("h4");
   var h5 = new tagbuilder("h5");
   var h6 = new tagbuilder("h6");
   h1.innerhtml.append(text);
   h2.innerhtml.append(text);
   h3.innerhtml.append(text);
   h4.innerhtml.append(text);
   h5.innerhtml.append(text);
   h6.innerhtml.append(text);
   output.content.appendhtml(h1);
   output.content.appendhtml(h2);
   output.content.appendhtml(h3);
   output.content.appendhtml(h4);
   output.content.appendhtml(h5);
   output.content.appendhtml(h6);
  }


(3)在_viewimports.cshtml导入类命名空间

@addtaghelper *,taghelpersample

(4)在cshtml中使用标签助手

<text-collection color="red"></text-collection>
<text-collection color="blue"></text-collection>
<text-collection color="#666"></text-collection>

(5)调试效果

ok,今天关于taghelper就分享到这。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网