上一篇博客我講解了TagHelper的基本用法和自定義標籤的生成,那麼我就趁熱打鐵,和你們分享一下TagHelper的高級用法~~,你們也能夠在個人博客下隨意留言。html
對於初步接觸asp.net core的騷年能夠看看我對TagHelper的瞭解和見解:git
《asp.net core新特性(1):TagHelper》github
以後,我也會繼續撰寫博文,繼續分享asp.net core的一些新特性,好比DI,ViewComponent以及bower等asp.net mvc中沒有的新東西。express
ok,我們就開始吧~~mvc
在以前我對TagHelper的分享當中說起了,TagHelper可以去替代原來在@Html幫助類中的一些功能,好比form,a等標籤,並且寫在html代碼中更加的舒服,符合html的語法。asp.net
<!--標籤助手版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中的屬性名,便可自動生成對應的控件類型和填入默認值。async
ok,咱們來嘗試一下。ide
(1)建立ViewModel類post
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就分享到這~~