上一篇博客《asp.net core新特性(1):TagHelper》我讲解了TagHelper的基本用法和自定义标签的生成,那么我就趁热打铁,和大家分享一下TagHelper的高级用法~~,大家也可以在我的博客下随意留言。对于初步接触asp.net core的骚年可以看看我对TagHelper的了解和看法:《asp.net core新特性(1):TagHelper》

  之后,我也会继续撰写博文,继续分享asp.net core的一些新特性,比如DI,ViewComponent以及bower等asp.net mvc中没有的新东西。

  ok,咱们就开始吧~~

  在之前我对TagHelper的分享当中提及了,TagHelper能够去替代原来在@Html帮助类中的一些功能,比如form,a等标签,而且写在html代码中更加的舒服,符合html的语法。

<!--标签助手版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" }))

{

}

 那么,在Html帮助类中最有用的Model与Tag的转换,自动表单的生成,微软是否也给出了解决方案呢?答案是肯定的。Microsoft还专门分出了单独的说明页面来讲述TagHelper的自动表单生成,英文功底好的同学可以直接查看MS的官方文档《Introduction to using tag helpers in forms in ASP.NET Core》。

  文档中提及了对于表单控件,我们可以直接在asp-for属性中直接填写Model中的属性名,即可自动生成对应的控件类型和填入默认值。

  ok,我们来尝试一下。

  (1)创建ViewModel类

public class SignUpViewModel

{

[Required]

[Display(Name ="用户名")]

[MaxLength(30,ErrorMessage = "用户名不能超过30")]

public string UserName { get; set; }

[Required]

[DataType(DataType.Password)]

[RegularExpression(@"((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^$",ErrorMessage ="密码至少包含两种以上字符")]

[Display(Name ="密码")]

public string Password { get; set; }

[DataType(DataType.MultilineText)]

public string Description { get; set; }

}

对于写过asp.net mvc的开发者肯定不会陌生这种验证方式~~

  (2)编写TagHelper标签

  为了与Html区分,我写了两者的比较版本

<form asp-controller="Home" asp-action="SignUp" method="post" class="form-horizontal">

<div class="form-group">

<label asp-for="UserName"></label>

<input asp-for="UserName" />

<span asp-validation-for="UserName"></span>

</div>

<div class="form-group">

@Html.LabelFor(m=>m.Password)

@Html.PasswordFor(m=>m.Password)

@Html.ValidationMessageFor(m=>m.Password)

</div>

<div class="form-group">

<label asp-for="Description"></label>

<textarea asp-for="Description"></textarea>

<span asp-validation-for="Description"></span>

</div>

<div class="form-group">

<input type="submit" value="提交" />

<input type="reset" value="重置" />

</div>

</form>

(3)验证表单

public IActionResult SignUp(SignUpViewModel model)

{

if (ModelState.IsValid)

{

return RedirectToAction("Index");

}

else

{

return RedirectToAction("Index",model);

}

}

(4)结果

  

  ok,如果觉得这样就结束了,那么就不算TagHelper高级应用,那只能充其量在翻译MS的文档罢了。

  那么,重点来了,既然MS能让我们创建自定义TagHelper,那我为什么不能在TagHelper当中使用Model的值呢?于是我开始在asp.net core开源github项目中寻找,终于是找到了ImputTagHelper的源码。

  在源码中,由三个对象一起来完成标签的生成

protected IHtmlGenerator Generator { get; }

[HtmlAttributeNotBound]

[ViewContext]

public ViewContext ViewContext { get; set; }

/// <summary>

/// An expression to be evaluated against the current model.

/// </summary>

[HtmlAttributeName(ForAttributeName)]

public ModelExpression For { get; set; }

三个对象均是通过依赖注入的方式来实现对象的生成。

  (1)其中Generator为发生器,负责生成各种类型的标签

  (2)ViewContext为视图上下文,获取视图上下文相关信息

  (3)For获取到当前Model的相关信息,包括Required等关键信息

  有了这三个标签,我们也可以在自定义的标签助手中获取你想要的Model信息,比如我可以向form中填入Model信息,让标签助手自动生成form表单中的所有内容;也可以向ul标签中填入树信息,让其自动生成树列表等等

  如下就是我编写的自动生成表单

//自定义标签助手名为bg-form

[HtmlTargetElement("bg-form")]

public class FormTagHelper : TagHelper

{

[ViewContext]

[HtmlAttributeNotBound]

public ViewContext ViewContext { get; set; }

[HtmlAttributeName("asp-for")]

public ModelExpression For { get; set; }

protected IHtmlGenerator Generator { get; }

public FormTagHelper(IHtmlGenerator generator)

{

Generator = generator;

}

[HtmlAttributeName("asp-controller")]

public string Controller { get; set; }

[HtmlAttributeName("asp-action")]

public string Action { get; set; }

//异步方法

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)

{

output.TagName = "form";

if (!string.IsNullOrWhiteSpace(Controller))

{

output.Attributes.Add("action", "/" + Controller + "/" + Action);

}

output.Attributes.Add("class", "form-horizontal");

//获取子属性

var props = For.ModelExplorer.Properties;

foreach (var prop in props)

{

//生成表单

var div = new TagBuilder("div");

div.AddCssClass("form-group");

var label = Generator.GenerateLabel(ViewContext, prop, null, prop.Metadata.DisplayName, null);

var input = Generator.GenerateTextBox(ViewContext, prop, prop.Metadata.PropertyName, null, null, null);

var span = Generator.GenerateValidationMessage(ViewContext, prop, prop.Metadata.PropertyName, null, ViewContext.ValidationMessageElement, null);

div.InnerHtml.AppendHtml(label);

div.InnerHtml.AppendHtml(input);

div.InnerHtml.AppendHtml(span);

output.Content.AppendHtml(div);

}

//添加按钮

var btn = new TagBuilder("div");

btn.AddCssClass("form-group");

var submit = new TagBuilder("input");

submit.Attributes.Add("type", "submit");

submit.Attributes.Add("value", "提交");

var reset = new TagBuilder("input");

reset.Attributes.Add("type", "reset");

reset.Attributes.Add("value", "重置");

btn.InnerHtml.AppendHtml(submit);

btn.InnerHtml.AppendHtml(reset);

output.Content.AppendHtml(btn);

//将原有的内容添加到标签内部

output.Content.AppendHtml(await output.GetChildContentAsync());

}

}

只要在html加入

<bg-form asp-controller="Home" asp-action="SignUp" asp-for="@Model"></bg-form>

即可自动生成表单

  Over,今天关于TagHelper就分享到这~~

原文地址:http://www.cnblogs.com/billming/p/7148226.html


.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注

asp.net core高级应用:TagHelper+Form相关推荐

  1. WTM(ASP.NET Core)使用ASP.NET Core自带TagHelper显示模型验证消息

    WTM框架使用TagHelper提供了丰富的前端控件,目前框架只支持LayUI,后期会增加更多框架整体的运转并不依赖于LayUI,开发人员可以使用最普通的Html来编写页面,框架提供的控件只是简化编写 ...

  2. html表格标签高级应用,asp.net core标签助手的高级用法TagHelper+Form

    上一篇博客我讲解了TagHelper的基本用法和自定义标签的生成,那么我就趁热打铁,和大家分享一下TagHelper的高级用法~~,大家也可以在我的博客下随意留言. 对于初步接触asp.net cor ...

  3. ASP.NET Core 高级(一)【.NET 的开放 Web 接口 (OWIN)】

    ASP.NET Core 中 .NET 的开放 Web 接口 (OWIN) ASP.NET Core 支持 .NET 的开放 Web 接口 (OWIN). OWIN 允许 Web 应用从 Web 服务 ...

  4. 【面试】ASP.NET Core+Redis+Mysql面试题答案

    .NET Core 1.如何在ASP.NET Core中激活Session功能   写的好啊,Inb哥,我是废物 2.什么是中间件   中间件是介于应用系统和系统软件之间的一类软件,它使用系统软件所提 ...

  5. ASP.NET Core分布式项目实战(课程介绍,MVP,瀑布与敏捷)--学习笔记

    任务1:课程介绍 课程目标: 1.进一步理解 ASP.NET Core 授权认证框架.MVC 管道 2.掌握 Oauth2,结合 Identity Sercer4 实现 OAuth2 和 OpenID ...

  6. 为什么 web 开发人员需要迁移到. NET Core, 并使用 ASP.NET Core MVC 构建 web 和 API

    2018 .NET开发者调查报告: .NET Core 是怎么样的状态,这里我们看到了还有非常多的.net开发人员还在观望,本文给大家一个建议.这仅代表我的个人意见, 我有充分的理由推荐.net 程序 ...

  7. (更新时间)2021年5月18日 ASP.NET Core 笔试题

    .NET Core笔试题 文章目录 .NET Core笔试题 1.如何在ASP.NET Core中激活Session功能? 2.什么是中间件? 3.Applicationbuilder的Use和Run ...

  8. 【笔记】ASP.NET Core技术内幕与项目实现:基于DDD与前后端分离

    最近在写论文,想使用ASP.NET Core Web API技术,但对它还不是很熟,鉴权组件也没用过,于是在网上查找资料,发现了杨中科老师写的这本书(微信读书上可以免费看),说起来我最初自学C#时看过 ...

  9. ASP.NET Core教程

    第一章 .Net Core入门 1 .net core入门 第二章 .Net Core重难点知识 2.1 C#新语法 2.2 异步编程 2.3 LINQ 第三章 .Net Core核心基础组件 3.1 ...

最新文章

  1. 百度开源,分布式配置中心
  2. CSS3秘笈第三版涵盖HTML5学习笔记13~17章
  3. Spring与其他Web框架集成
  4. mysql grant 不想让用户看到 系统默认 mysql_MYSQL用户权限管理GRANT使用
  5. Scala入门到精通——第十四节 Case Class与模式匹配(一)
  6. Android高性能ORM数据库DBFlow入门
  7. Android10弹出截屏对话框,Android一个美丽而聪明的警告对话框SweetAlert
  8. CSS的七种基本选择器及其权值
  9. 在测试中发现错误,不要着急去改,静下心来,想一想错误的关联性( 错误展开确认 )。
  10. 知道半径 两点角度 怎么求坐标
  11. Spark-Streaming
  12. jquery的层次选择器
  13. 如何保证软件质量?汽车软件基于模型开发的十个问题与质量工具推荐
  14. Atitit sdk封装的艺术 艾提拉著 1. 重要模块8个 1 1.1. Collections集合,core,net,io,Script,sql,text,fp 1 1.2. 全部模块25
  15. Snagit--高难度、多功能截图,有了它截图不求人!
  16. 文件传输的服务器软件有哪些,好用的数据传输软件有哪些?专业的数据传输软件排行榜...
  17. Supporting hyperplane
  18. linux权限777什么意思,chmod 权限777是什么意思
  19. android商品上架功能实现,Android仿京东、天猫app的商品详情页的布局架构, 以及功能实现...
  20. 为什么越来越多的人放弃欧美市场,转做Starday日本市场?

热门文章

  1. 数据库设计-基础-1-教务科研申报系统设计UML用例图
  2. 远程连接mysql速度慢的解决方法
  3. 使用gulp-connect实现web服务器
  4. Mysql Engine【innodb,myisam】
  5. 使用Visual Studio 创建可视Web Part部件
  6. 葬身李刚儿子车轮下的漂亮女孩
  7. 通过Dapr实现一个简单的基于.net的微服务电商系统(十八)——服务保护之多级缓存...
  8. ABP vNext微服务架构详细教程——简介
  9. Dapr + .NET Core实战(二) 服务调用
  10. NET问答: C# 中是否有 format json 的类库?