In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about how to use TagHelper+Form in asp.net core. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
TagHelper can replace some of the functions originally in the @ Html helper class, such as tags such as form,a, and it is more comfortable to write in html code, in line with html syntax.
@ using (Html.BeginForm ("Index", "Home", FormMethod.Post, new {Class = "form-horizontal"}))
{
}
So, in the Html help class, the most useful conversion between Model and Tag, automatic form generation, does Microsoft also give a solution? The answer is yes. Microsoft also has a separate description page to describe the automatic form generation of TagHelper. Students with good English skills can directly view the official document "Introduction to using tag helpers in forms in ASP.NET Core" of MS.
It is mentioned in the document that for form controls, we can fill in the property name in Model directly in the asp-for property to automatically generate the corresponding control type and fill in the default value.
Ok, let's give it a try.
(1) create a ViewModel class
Public class SignUpViewModel
{
[Required]
[Display (Name = "user name")]
[MaxLength (30dErrorMessage = "user name cannot exceed 30")]
Public string UserName {get; set;}
[Required]
[DataType (DataType.Password)]
[Regular_Expression (@ "((? = .*\ d) (? = .*\ D) | (? = .* [a-zA-Z]) (? = .* [^ a-zA-Z]) ^ $", ErrorMessage = "password contains at least two characters")]
[Display (Name = "password")]
Public string Password {get; set;}
[DataType (DataType.MultilineText)]
Public string Description {get; set;}
}
Developers who have written asp.net mvc will certainly be familiar with this kind of verification.
(2) write TagHelper tags
In order to distinguish from Html, I wrote a comparative version of the two.
@ Html.LabelFor (m = > m.Password)
@ Html.PasswordFor (m = > m.Password)
@ Html.ValidationMessageFor (m = > m.Password)
(3) validate the form
Public IActionResult SignUp (SignUpViewModel model)
{
If (ModelState.IsValid)
{
Return RedirectToAction ("Index")
}
Else
{
Return RedirectToAction ("Index", model)
}
}
(4) results
Ok, if you think it's over, then it's not a TagHelper advanced application, it's just translating MS documents at best.
So, the point is, since MS allows us to create custom TagHelper, why can't I use the value of Model in TagHelper? So I started looking in the asp.net core open source github project, and finally found the source code of ImputTagHelper.
In the source code, the label is generated by three objects together.
Protected IHtmlGenerator Generator {get;}
[HtmlAttributeNotBound]
[ViewContext]
Public ViewContext ViewContext {get; set;}
/ / /
/ An expression to be evaluated against the current model.
/ / /
[HtmlAttributeName (ForAttributeName)]
Public ModelExpression For {get; set;}
All three objects are generated by dependency injection.
(1) where Generator is the generator, which is responsible for generating various types of tags
(2) ViewContext is the view context to obtain the view context-related information.
(3) For obtains relevant information about the current Model, including key information such as Required.
With these three tags, we can also get the Model information you want in the custom tag assistant. For example, I can fill in the Model information into the form and let the tag assistant automatically generate all the content in the form form; or we can fill in the tree information into the ul tag to automatically generate the tree list, and so on.
Here is the auto-generated form I wrote
/ / Custom tag Assistant name is 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;}
/ / Asynchronous method
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")
/ / get child attributes
Var props = For.ModelExplorer.Properties
Foreach (var prop in props)
{
/ / generate the form
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)
}
/ / add button
Var btn = new TagBuilder ("div")
Btn.AddCssClass ("form-group")
Var submit = new TagBuilder ("input")
Submit.Attributes.Add ("type", "submit")
Submit.Attributes.Add ("value", "submit")
Var reset = new TagBuilder ("input")
Reset.Attributes.Add ("type", "reset")
Reset.Attributes.Add ("value", "reset")
Btn.InnerHtml.AppendHtml (submit)
Btn.InnerHtml.AppendHtml (reset)
Output.Content.AppendHtml (btn)
/ / add the original content to the inside of the tag
Output.Content.AppendHtml (await output.GetChildContentAsync ())
}
}
Just join in html
The form can be generated automatically.
The above is how to use TagHelper+Form in asp.net core. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.