"netcore Study notes taghelper" Customize your own Taghelper

Source: Internet
Author: User
Tags naming convention

Since the launch of netcore, many people have been chasing and paying attention, making it a one-time citizen in asp. I was one of them, at best a pseudo-fan, because the attention is not too much, not deep enough.

today, the main records of the learning notes are: How to customize their own taghelper. Words not much to say, straight into the topic:

1. Define the interface

 public Interface Icountryservice    {        IEnumerable<CountryModel> GetAll ();    }

2. Define the interface implementation class

  public classCountryservice:icountryservice {Private StaticIenumerable<countrymodel> countrylist =NewList<countrymodel>()        {            NewCountrymodel () {id=1, enname=" china", cnname="China", code=" china"},            NewCountrymodel () {id=2, enname="Japan", cnname="Japan", code="Japan"},            NewCountrymodel () {id=3, enname="America", cnname="United States", code="America"},        };  publicIenumerable<countrymodel>GetAll () {returncountrylist; }    }

3. Injection

For injection, say a few more words. in. net core, there are several common ways of injecting: (personal understanding, not treatise, daniel):

addtransient: each request Icountryservice, an object is generated;

addsingleton: as the name implies, a singleton pattern, throughout the life cycle of the application, from start--->End;

addscoped: can be understood as the entire life cycle through the current Request. How to understand, that is, when you first request a Icountryservice object; in another part of the request, if you use the other logic of icountryservice, you will also share the first generated Object. Until the end of the life cycle of this Request. In my opinion, it is equivalent to a singleton pattern within the life cycle;

  

 public void configureservices (iservicecollection services) {    // the others      Services. AddTransient<icountryservice, countryservice>();}

4. Customize your own Taghelper method

 //Custom Taghelper class, The main is to inherit taghelper, located under the namespace Microsoft.AspNetCore.Razor.TagHelpers  public classCountrylisttaghelper:taghelper {Private ReadOnlyIcountryservice _countryservice;  public stringSelectedValue {Get;Set; } Custom properties, which will be used in subsequent publiccountrylisttaghelper (icountryservice countryservice) {_countryservice=countryservice; }         public Override voidProcess (taghelpercontext context, taghelperoutput output) {output. TagName="Select"; Output.            Content.clear (); foreach(varIteminch_countryservice.getall ()) {                varseleted =""; if(selectedvalue! =NULL&&selectedvalue.equals (item. Code, Stringcomparison.currentcultureignorecase)) {seleted="selected=\ "selected\""; }                varListItem = $"<option value=\ "{item. Code}\ "{seleted}>{item. Cnname}-{item.enname}</option>"; Output.            Content.appendhtml (listItem); }            //Base. Process (context, output);        }    }

Because you need to inherit taghelper, you need to introduce the following dependency packages (if you develop with the VS2015 tool, you will be prompted to install what depends on it):

"Microsoft.AspNetCore.Razor.Runtime": "1.0.0", "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0"

In fact, this is only used in the synchronous method, there is an asynchronous method, specifically defined and described as Follows:
namespacemicrosoft.aspnetcore.razor.taghelpers{/// <summary>Class used to filter matching HTML elements.</summary>   public Abstract classTaghelper:itaghelper {protectedTaghelper (); /// <inheritdoc/>     public Virtual voidInit (taghelpercontext context); /// <summary>    ///synchronously executes the<see cref= "t:microsoft.aspnetcore.razor.taghelpers.taghelper"/>With the given<paramref name= "context"/> and/// <paramref name= "output"/>. /// </summary>    /// <param name= "context" >Contains information associated with the current HTML tag.</param>    /// <param name= "output" >A stateful HTML element used to generate an HTML Tag.</param>     public Virtual voidProcess (taghelpercontext context, taghelperoutput output); /// <summary>    ///asynchronously executes the<see cref= "t:microsoft.aspnetcore.razor.taghelpers.taghelper"/>With the given<paramref name= "context"/> and/// <paramref name= "output"/>. /// </summary>    /// <param name= "context" >Contains information associated with the current HTML tag.</param>    /// <param name= "output" >A stateful HTML element used to generate an HTML Tag.</param>    /// <returns>A<see cref= "t:system.threading.tasks.task"/>That on completion updates the<paramref name= "output"/>.</returns>    /// <remarks>by default this calls into<see cref= "m:microsoft.aspnetcore.razor.taghelpers.taghelper.process ( Microsoft.aspnetcore.razor.taghelpers.taghelpercontext,microsoft.aspnetcore.razor.taghelpers.taghelperoutput) " />.</remarks>    /// .     public VirtualTask processasync(taghelpercontext context, taghelperoutput output); /// <inheritdoc/>    /// <remarks>Default Order is<c>0</c>.</remarks>     public Virtual intOrder {Get; } }}

The wheel is built so that it needs to be tested to see if it can Run.

5. Application Testing

I put this reference in a single view page, (the following three ways, any one can be selected)

Format: @addTagHelper Typename,assemblyname
// Way one, All Taghelper under the assembly@addTagHelper *, Todolist.project
// mode two, specifying the path explicitly " Todolist.project.extensions.countrylisttaghelper,todolist.project " // method three, Fuzzy matching " Todolist.project.extensions.countrylist*,todolist.project "

tags are introduced in the following ways:

<country-list selected-value= "china" ></country-list>

As follows:

The generated HTML code is:

<Select><optionvalue= "china"selected= "selected">China-china</option><optionvalue= "Japan">Japan-japan</option><optionvalue= "America">United States-america</option></Select>

In fact, there are two places involved, one is the creation of the project, the self-_viewimports.cshtml, what is this file for? Personal understanding is some of the namespaces that need to be imported in VIEW. and is used Globally.

If you are using a single view, add it to the corresponding view Page.

For the Label's naming convention:

Presumably: If there are multiple uppercase letters (such as countrylist), then all uppercase will be converted to lowercase, and then split the word (for example: countrylist--->country-list);

If it is a single word, go directly to lowercase, (such as emailtaghelper---> email);

If you want to specify HTML tag properties yourself, You can add a property tag on taghelper:

    [htmltargetelement ("country-lists")]      public class Countrylisttaghelper:taghelper

When used, it is <country-lists selected-value= "china" ></country-lists>

6. PostScript

There are some questions, I probably turned over the source code, and did not find the custom taghelper, the naming rules used in the previous page look Like. I saw some examples on the notes on and off. It makes me a little uncomfortable. (who found it, please tell me where it is)

In fact, there are some self-taghelper, such as:

Resources:

Https://docs.asp.net/en/latest/mvc/views/tag-helpers/intro.html

Http://www.cnblogs.com/TomXu/p/4496480.html

"netcore Study notes taghelper" Customize your own Taghelper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.