Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of TagHelper function in ASP.NET5 and MVC6

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shares with you the content of a sample analysis of TagHelper functionality in ASP.NET5 and MVC6. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

In the new version of MVC6, Microsoft provides powerful TagHelper features to get rid of the following bloated code:

Html.LabelFor (model = > model.FullName) @ Html.EditFor (model = > model.FullName) @ Html.ValidationMessageFor (model = > model.FullName)

After introducing the new feature TagHelper, we only need to define it in this way. The code is as follows:

@ addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" / * the namespace where TagHelper is located needs to be referenced first * /

In this way, the server-side code is thrown away, the use of custom html attributes appears to be more semantic, and the front-end staff is also very comfortable to drive, which greatly improves the efficiency of front-end developers.

In the default TagHelper implementation, different elements support different custom attributes for different purposes. For example, most elements support asp-for, while an element supports asp-controller and asp-action, etc. The input element is the most powerful, supporting various types of type and related formats. For detailed implementation, please refer to the table content in the following section.

Element A

Attribute describes the name of the asp-controllerController, the name of the asp-actionAction, the fragment name of the Hostasp-fragmentURL of the asp-host website, the asp-protocol website protocol (http or https) asp-routeRoute name asp-route-

Href default property, if href has a value, none of the other properties can set any value.

Form element

Property describes the name of asp-controllerController, the name of asp-actionAction, asp-anti-forgery

Asp-route-

Action default property, if action has a value, none of the other properties can set any value.

Input element

Property describes the name of the asp-for model field asp-format sets the Type format as follows: format standard type HiddenInputhiddenPasswordpasswordTexttextPhoneNumbertelUrlurlEmailAddressemailDatedateDateTimedatetimeDateTime-localdatetime-localTimetimeByte/SByte/Int16/UInt16/Int32/UInt32/Int64/UInt64/Single/ DoublenumberBooleancheckboxDecimaltextStringtextIFormFilefileIEnumerle`IFormFilefile

The specific format of time is as follows:

Property description 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 element

Property describes the name of the asp-for model field

Textarea element

Property describes the name of the asp-for model field

Span element

Property describes the name of the asp-validation-for model field

Div element

Property description asp-validation-aummaryValidationSummary enumerated value:

ValidationSummary.All

ValidationSummary.ModelOnly

ValidationSummary.None .

Verify the description type and render the div element only if ValidationSummary.All and ValidationSummary.ModelOnly are selected.

Select element

Attribute description asp-for model field name asp-items model field name

Link element

Property description asp-href-include

Asp-href-exclude

Asp-fallback-href default href alternate address asp-fallback-href-include when loading fails

Asp-fallback-href-exclude

Asp-fallback-test-class determines the class style used when loading failed asp-fallback-test-property determines the attribute in class style used when loading failed asp-fallback-test-value determines the value asp-file-version corresponding to the attribute in class style used when loading failed

The address of the css file that href loads by default.

An example of the use of link is as follows. For example, we define the following code:

Then the code indicates that the css file on the aspnetcdn.com is loaded by default, and then the css file in the local website is loaded if the load fails. The judgment condition of the load failure is: detect that the carousel-caption style is very applied, that is, whether the display attribute of the element with this style is equal to none. After running the website, the generated html of this code is as follows:

! 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('') } } }("display", "none", ["\/lib\/bootstrap-touch-carousel\/css\/bootstrap-touch-carousel.css"]); 从中,我们看到,生成的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文件是否加载成功,示例如下: 生成后的HTML代码,相对比较简单,示例如下: (window.jQuery||[xss_clean]("")); 多生成了一个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元素标签就可以了,示例如下: 在上述代码中,我们定于,如果是Development环境就使用本地的js文件,否则(Staging或Production环境)就先加载cdn的文件(只不过还留有备用方案)。 该names里的值判断依据是,查找IHostingEnvironment的EnvironmentName属性,并与其进行比较,然后再进行相应的处理。 自定义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); / / Delete all attributes because output.Attributes.Clear () can already be automatically generated in the route; output.Attributes ["href"] = UrlHelper.Action (Action, Controller, methodParameters); output.PreContent.SetContent ("My");}

two。 Automatically recognize links in Text text and extract them

[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", "$0"));}}

3. Conditional judgment

Define a condiction and display the element only if the conditions are met. The example is as follows (this element is displayed only if Model.Approved is true):

©@ Model.CopyrightYear-My ASP.NET Application

The implementation code is as follows:

[TargetElement ("div")] [TargetElement ("style")] [TargetElement ("p")] public class ConditionTagHelper: TagHelper {public bool? Condition {get; set;} public override void Process (TagHelperContext context, TagHelperOutput output) {/ / if condition is set and the value is false, the element if (Condition.HasValue & &! Condition.Value) {output.SuppressOutput ();} is not rendered.

4. TagHelper of a custom element

If we want to define a TagHelper for a custom element, we need to comply with the convention specification, and the sample code is as follows:

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 (

Version: {0}

"+ Environment.NewLine +"

Copyright Year: {1}

"+ Environment.NewLine +"

Approved: {2}

"+ Environment.NewLine +"

Number of tags to show: {3}

"+ Environment.NewLine, Info.Version.ToString (), Info.CopyrightYear.ToString (), Info.Approved.ToString (), Info.TagsToShow.ToString ()); output.SelfClosing = false;}}

When using it, we need to use the website-information tag and assign the info attribute a strongly typed value, as shown in the following example:

The result of the rendering is to render as a section element with four p elements.

Thank you for reading! This is the end of this article on "sample Analysis of TagHelper functions in ASP.NET5 and MVC6". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report