asp.net core標(biāo)簽助手的高級用法TagHelper+Form
上一篇博客我講解了TagHelper的基本用法和自定義標(biāo)簽的生成,那么我就趁熱打鐵,和大家分享一下TagHelper的高級用法~~,大家也可以在我的博客下隨意留言。
對于初步接觸asp.net core的騷年可以看看我對TagHelper的了解和看法:
《asp.net core新特性(1):TagHelper》
之后,我也會繼續(xù)撰寫博文,繼續(xù)分享asp.net core的一些新特性,比如DI,ViewComponent以及bower等asp.net mvc中沒有的新東西。
ok,咱們就開始吧~~
在之前我對TagHelper的分享當(dāng)中提及了,TagHelper能夠去替代原來在@Html幫助類中的一些功能,比如form,a等標(biāo)簽,而且寫在html代碼中更加的舒服,符合html的語法。
<!--標(biāo)簽助手版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的轉(zhuǎn)換,自動表單的生成,微軟是否也給出了解決方案呢?答案是肯定的。Microsoft還專門分出了單獨的說明頁面來講述TagHelper的自動表單生成,英文功底好的同學(xué)可以直接查看MS的官方文檔《Introduction to using tag helpers in forms in ASP.NET Core》。
文檔中提及了對于表單控件,我們可以直接在asp-for屬性中直接填寫Model中的屬性名,即可自動生成對應(yīng)的控件類型和填入默認(rèn)值。
ok,我們來嘗試一下。
(1)創(chuàng)建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的開發(fā)者肯定不會陌生這種驗證方式~~
(2)編寫TagHelper標(biāo)簽
為了與Html區(qū)分,我寫了兩者的比較版本
<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)結(jié)果

ok,如果覺得這樣就結(jié)束了,那么就不算TagHelper高級應(yīng)用,那只能充其量在翻譯MS的文檔罷了。
那么,重點來了,既然MS能讓我們創(chuàng)建自定義TagHelper,那我為什么不能在TagHelper當(dāng)中使用Model的值呢?于是我開始在asp.net core開源github項目中尋找,終于是找到了ImputTagHelper的源碼。
在源碼中,由三個對象一起來完成標(biāo)簽的生成
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; }
三個對象均是通過依賴注入的方式來實現(xiàn)對象的生成。
(1)其中Generator為發(fā)生器,負(fù)責(zé)生成各種類型的標(biāo)簽
(2)ViewContext為視圖上下文,獲取視圖上下文相關(guān)信息
(3)For獲取到當(dāng)前Model的相關(guān)信息,包括Required等關(guān)鍵信息
有了這三個標(biāo)簽,我們也可以在自定義的標(biāo)簽助手中獲取你想要的Model信息,比如我可以向form中填入Model信息,讓標(biāo)簽助手自動生成form表單中的所有內(nèi)容;也可以向ul標(biāo)簽中填入樹信息,讓其自動生成樹列表等等
如下就是我編寫的自動生成表單
//自定義標(biāo)簽助手名為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);
//將原有的內(nèi)容添加到標(biāo)簽內(nèi)部
output.Content.AppendHtml(await output.GetChildContentAsync());
}
}
只要在html加入
<bg-form asp-controller="Home" asp-action="SignUp" asp-for="@Model"> </bg-form>
即可自動生成表單

Over,今天關(guān)于TagHelper就分享到這
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET小結(jié)之MVC, MVP, MVVM比較以及區(qū)別(一)
MVC, MVP和MVVM都是用來解決界面呈現(xiàn)和邏輯代碼分離而出現(xiàn)的模式。以前只是對它們有部分的了解,沒有深入的研究過,對于一些里面的概念和區(qū)別也是一知半解。現(xiàn)在一邊查資料,并結(jié)合自己的理解,來談一下對于這三種模式思想的理解,以及它們的區(qū)別。歡迎各位高手拍磚。2014-05-05
.Net微信網(wǎng)頁開發(fā)解決用戶在不同公眾號或在公眾號、移動應(yīng)用之間帳號統(tǒng)一問題
這篇文章主要介紹了.Net微信網(wǎng)頁開發(fā)解決用戶在不同公眾號或在公眾號、移動應(yīng)用之間帳號統(tǒng)一問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
asp.net DataSet轉(zhuǎn)換成josn并輸出示例
如何將DataSet轉(zhuǎn)換成josn并輸出,這是很多新手朋友們遇到的問題,下面有個不錯的示例,希望對大家有所幫助2014-01-01
repeater隔行換色與鼠標(biāo)停留在上面達(dá)到變色效果
鼠標(biāo)停留在上面是變成其他的顏色,很多新手朋友都想實現(xiàn)這種效果,可是無從下手,本文整理了一些解決技巧,感興趣的朋友可以參考下啊2013-01-01
asp.net生成高質(zhì)量縮略圖通用函數(shù)(c#代碼),支持多種生成方式
這兩天正在研究報表中餅圖的繪圖方法,文章中的某些做法值得參考.2008-08-08
.Net Core簡單使用Mvc內(nèi)置的Ioc(續(xù))
怎樣直接獲取Ioc中的實例對象,而不是以構(gòu)造函數(shù)的方式進(jìn)行獲取呢?這篇文章繼續(xù)為大家介紹.Net Core簡單使用Mvc內(nèi)置的Ioc2018-03-03
asp.net模板引擎Razor中cacheName的問題分析
這篇文章主要介紹了asp.net模板引擎Razor中cacheName的問題,實例分析了cacheName在提高編譯效率方面的使用技巧,需要的朋友可以參考下2015-06-06

