当前位置: 移动技术网 > IT编程>开发语言>.net > 解读ASP.NET 5 & MVC6系列教程(13):TagHelper

解读ASP.NET 5 & MVC6系列教程(13):TagHelper

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

查价狗,纳拉辛的学识之书,慢慢扒她衣服

在新版的mvc6中,微软提供了强大的taghelper功能,以便让我们摆脱如下的臃肿代码:

@html.labelfor(model => model.fullname)
@html.editfor(model => model.fullname)
@html.validationmessagefor(model => model.fullname)

引入新功能taghelper以后,我们只需要这样定义就可以了,代码如下:

@addtaghelper "*, microsoft.aspnet.mvc.taghelpers" /* 这里需要首先引用taghelper所在的命名空间 */

<label asp-for="fullname" class="control-label col-md-2"></label>
<div class="col-md-10">
 <input asp-for="fullname" class="form-control" />
 <span asp-validation-for="fullname"></span>
</div>

这种方式,抛去了服务器端代码,利用自定义html属性显得更加有语义,前端人员开起来也很舒服,极大地提高了前端开发人员的效率。

在默认的taghelper实现里,不同的元素支持不同的自定义属性,以实现不同的用途,例如大部分元素都支持asp-for,而a元素则支持asp-controllerasp-action等,input元素最强大的,支持各种类型的type以及相关的格式。详细实现,请参考如下章节中的表格内容。

a元素

属性 描述
asp-controller controller的名称
asp-action action的名称
asp-host 网站的host
asp-fragment url的fragment名称
asp-protocol 网站协议(http或https)
asp-route route名称
asp-route-
href 默认属性,如果href有值,则其它属性都不能设置任何值。

form元素

属性 描述
asp-controller controller的名称
asp-action action的名称
asp-anti-forgery
asp-route-
action 默认属性,如果action有值,则其它属性都不能设置任何值。

input元素

属性 描述
asp-for 模型字段的名称
asp-format 设置type格式,具体如下:
格式 标准类型
hiddeninput hidden
password password
text text
phonenumber tel
url url
emailaddress email
date date
datetime datetime
datetime-local datetime-local
time time
byte/sbyte/int16/uint16/int32/uint32/int64/uint64/single/double number
boolean checkbox
decimal text
string text
iformfile file
ienumerable`iformfile file

其中关于时间的具体格式如下:

属性 描述
date {0:yyyy-mm-dd}
datetime {0:yyyy-mm-ddthh:mm:ss.fffk}
datetime-local {0:yyyy-mm-ddthh:mm:ss.fff}
time {0:hh:mm:ss.fff}

label元素

属性 描述
asp-for 模型字段的名称

textarea元素

属性 描述
asp-for 模型字段的名称

span元素

属性 描述
asp-validation-for 模型字段的名称

div元素

属性 描述
asp-validation-aummary validationsummary枚举值:
validationsummary.all
validationsummary.modelonly
validationsummary.none。

验证描述类型,只有选择了validationsummary.all和validationsummary.modelonly才能渲染该div元素。

select元素

属性 描述
asp-for 模型字段名称
asp-items 模型字段名称

link元素

属性 描述
asp-href-include
asp-href-exclude
asp-fallback-href 默认href加载失败时的备用地址
asp-fallback-href-include
asp-fallback-href-exclude
asp-fallback-test-class 判断加载失败时用到的class样式
asp-fallback-test-property 判断加载失败时用到的class样式中的属性
asp-fallback-test-value 判断加载失败时用到的class样式中的属性对应的值
asp-file-version
href 默认加载的css文件地址。

link的使用示例如下,比如我们定义如下代码:

<link rel="stylesheet" 
href="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/bootstrap-touch-carousel.css"
asp-fallback-href="~/lib/bootstrap-touch-carousel/css/bootstrap-touch-carousel.css"
asp-fallback-test-class="carousel-caption" 
asp-fallback-test-property="display" 
asp-fallback-test-value="none" />

则该段代码表示,默认先加载aspnetcdn.com上的css文件,如果加载失败了,再加载本地网站里的css文件,加载失败的判断条件是:检测carousel-caption样式十分应用上了,即该应用了该样式的元素的display属性是否等于none。运行网站后,这段代码的生成html如下:

<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/bootstrap-touch-carousel.css" />
<meta name="x-stylesheet-fallback-test" class="carousel-caption" />
<script>
 !function (a, b, c) {
  var d, e = document,
   f = e.getelementsbytagname("script"),
   g = f[f.length - 1].previouselementsibling,
   h = e.defaultview && e.defaultview.getcomputedstyle ? e.defaultview.getcomputedstyle(g) : g.currentstyle;

  if (h && h[a] !== b) {
   for (d = 0; d < c.length; d++) {
    e.write('<link rel="stylesheet" href="' + c[d] + '"/>')
   }
  }
 }("display", "none", ["\/lib\/bootstrap-touch-carousel\/css\/bootstrap-touch-carousel.css"]);
</script>

从中,我们看到,生成的html代码在link元素之后多了两个元素,一个是带有class="carousel-caption"属性的meta元素,一个是script脚本标签。其主要原理是如下:

在meta元素上应用定义的carousel-caption样式。通过js代码检测该meta元素的display属性是否等于none。如果不等于none,重新加载本地的备用css文件。

注意,这里的js脚本是利用document.getelementsbytagname("script"),获取最后一个script标签的上一个兄弟元素的形式,来获取meta元素的。

script元素

属性 描述
asp-src-include
asp-src-exclude
asp-fallback-src 备用js文件地址
asp-fallback-src-include
asp-fallback-src-exclude
asp-fallback-test 判断默认js文件是否加载成功用到的对象
asp-file-version
src 默认的js文件地址。

script标签元素的fallback功能,和link元素记载css文件类型,只不过这里判断的不是class样式,而是检测某个对象是否存在,来判断默认的js文件是否加载成功,示例如下:

<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js"
 asp-fallback-src="~/lib/jquery/jquery.min.js"
 asp-fallback-test="window.jquery">
</script>

生成后的html代码,相对比较简单,示例如下:

<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js">
</script>
<script>(window.jquery||document.write("<script src=\"\/lib\/jquery\/jquery.min.js\"><\/script>"));</script>

多生成了一个script标签元素,然后判断jquery对象是否存在,如果不存在则表示加载失败,那就再加载本地的备用js文件。

cache

属性 描述
vary-by
vary-by-header
vary-by-query
vary-by-route
vary-by-cookie
vary-by-user
expires-on
expires-after
expires-sliding
priority
enabled .

利用environmenttaghelper来控制不同运行环境的输出结果

在很多情况下,我们想再开发环境使用一套配置信息,在生产环境又是另外一套,这时候就需要使用条件判断语句了,不过在新版的mvc中,使用environmenttaghelper提供的environment元素标签就可以了,示例如下:

<environment names="development">
 <script src="~/lib/jquery/jquery.js"></script>
 <script src="~/lib/bootstrap/js/bootstrap.js"></script>
 <script src="~/lib/hammer.js/hammer.js"></script>
 <script src="~/lib/bootstrap-touch-carousel/js/bootstrap-touch-carousel.js"></script>
</environment>
<environment names="staging,production">
 <script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js"
   asp-fallback-src="~/lib/jquery/jquery.min.js"
   asp-fallback-test="window.jquery">
 </script>
 <script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/bootstrap.min.js"
   asp-fallback-src="~/lib/bootstrap/js/bootstrap.min.js"
   asp-fallback-test="window.jquery">
 </script>
 <script src="//ajax.aspnetcdn.com/ajax/hammer.js/2.0.4/hammer.min.js"
   asp-fallback-src="~/lib/hammer.js/hammer.js"
   asp-fallback-test="window.hammer">
 </script>
 <script src="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/js/bootstrap-touch-carousel.js"
   asp-fallback-src="~/lib/bootstrap-touch-carousel/js/bootstrap-touch-carousel.js"
   asp-fallback-test="window.zepto">
 </script>
</environment>

在上述代码中,我们定于,如果是development环境就使用本地的js文件,否则(staging或production环境)就先加载cdn的文件(只不过还留有备用方案)。

该names里的值判断依据是,查找ihostingenvironmentenvironmentname属性,并与其进行比较,然后再进行相应的处理。

自定义taghelper

mvc所有taghelper的实现,都继承了microsoft.aspnet.razor.runtime.taghelpers.itaghelper接口,所以我们只要实现该接口就可以实现自定义的taghelper,该接口的定义如下:

public interface itaghelper
{
 int order { get; }
 task processasync(taghelpercontext context, taghelperoutput output);
}

不过,我们一般自定义的时候,只需要继承该接口的默认实现taghelper类,并重载其虚方法process方法即可,如下是几个示例,我们来详细研究一下。

1. 在a元素上直接支持controller和action属性

public class ataghelper : taghelper
{
 [activate]
 public iurlhelper urlhelper { get; set; }

 public string controller { get; set; }

 public string action { get; set; }

 public override void process(taghelpercontext context, taghelperoutput output)
 {
  if (controller != null && action != null)
  {
   var methodparameters = output.attributes.todictionary(attribute => attribute.key,
                 attribute => (object)attribute.value);

   // 删除所有的attributes,因为路由里已经可以自动生成了
   output.attributes.clear();

   output.attributes["href"] = urlhelper.action(action, controller, methodparameters);

   output.precontent.setcontent("my ");
  }
 }
}

2. 自动识别text文本中的链接,并提取出来

[targetelement("p")]
public class autolinkertaghelper : taghelper
{
 public override async task processasync(taghelpercontext context, taghelperoutput output)
 {
  var childcontent = await context.getchildcontentasync();

  // find urls in the content and replace them with their anchor tag equivalent.
  output.content.setcontent(regex.replace(
   childcontent.getcontent(),
   @"\b(?:https?://|www\.)(\s+)\b",
   "<strong><a target=\"_blank\" href=\"http://$0\">$0</a></strong>"));
 }
}

3. 条件判断

定义一个condiction,符合条件才显示该元素,示例如下(只有model.approved为true时才显示该元素):

<p condition="model.approved" >© @model.copyrightyear - my asp.net application</p>

实现代码如下:

[targetelement("div")]
[targetelement("style")]
[targetelement("p")]
public class conditiontaghelper : taghelper
{
 public bool? condition { get; set; }

 public override void process(taghelpercontext context, taghelperoutput output)
 {
  // 如果设置了condition,并且该值为false,则不渲染该元素
  if (condition.hasvalue && !condition.value)
  {
   output.suppressoutput();
  }
 }
}

4. 自定义元素的taghelper

如果我们要为自定义元素定义taghelper,则我们要符合约定规范,示例代码如下:

public class websiteinformationtaghelper : taghelper
{
 public websitecontext info { get; set; }

 public override void process(taghelpercontext context, taghelperoutput output)
 {
  output.tagname = "section";
  output.postcontent.setcontent(string.format(
   "<p><strong>version:</strong> {0}</p>" + environment.newline +
   "<p><strong>copyright year:</strong> {1}</p>" + environment.newline +
   "<p><strong>approved:</strong> {2}</p>" + environment.newline +
   "<p><strong>number of tags to show:</strong> {3}</p>" + environment.newline,
   info.version.tostring(),
   info.copyrightyear.tostring(),
   info.approved.tostring(),
   info.tagstoshow.tostring()));
  output.selfclosing = false;
 }
}

则使用的时候,我们需要使用website-information标签,并将info属性赋值一个强类型的值,示例如下:

<website-information info="new websitecontext {
        version = new version(1, 1),
        copyrightyear = 1990,
        approved = true,
        tagstoshow = 30 }"/>

其渲染结果,则是渲染成一个包含4个p元素的section元素。

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

相关文章:

验证码:
移动技术网