Interpretation of ASP.net 5 & MVC6 series: Taghelper_ self-study process

Source: Internet
Author: User
Tags datetime touch

In the new version of MVC6, Microsoft offers a powerful Taghelper feature that lets us 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 just need to define this, and the code is as follows:

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"/* * Here you need to first refer to the namespace where Taghelper is located * * *

<label asp-for= "FullName" class= "Control-label col-md-2" ></label>
<div class= "col-md-10" >
 <input asp-for= " FullName "class=" Form-control "/>
 <span asp-validation-for=" FullName "></span>
</div>

This way, the server-side code is thrown away, the custom HTML attribute is more semantically made, and the front-end staff is comfortable to drive, greatly improving the efficiency of the front-end developers.

In the default Taghelper implementation, different elements support different custom attributes for different purposes, for example, most elements are supported asp-for , and the A element supports asp-controller and asp-action so on, and the input element is the most powerful, supporting various types of type and associated formats. For detailed implementation, refer to the table contents in the following section.

A element

Property Description
Asp-controller Name of Controller
Asp-action The name of the action
Asp-host The host of the website
Asp-fragment Fragment name of the URL
Asp-protocol Web site Protocol (HTTP or HTTPS)
Asp-route Route Name
asp-route-
Href Default property, if HREF has a value, no other properties can set any value.

Form element

Property Description
Asp-controller Name of Controller
Asp-action The name of the action
Asp-anti-forgery
asp-route-
Action Default property, if the action has a value, no other property can set any value.

INPUT element

Property Description
Asp-for Name of the Model field
Asp-format Set the type format, as follows:
format Standard Type
Hiddeninput Hidden
Password Password
Text Text
PhoneNumber Tel
Url Url
EmailAddress Email
Date Date
Datetime Datetime
Datetime-local Datetime-local
Time Time
Byte/sbyte/int16/uint16/int32/uint32/int64/uint64/single/double Number
Boolean CheckBox
Decimal Text
String Text
Iformfile File
IEnumerable ' Iformfile File

The specific format for the 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 Description
Asp-for Name of the Model field

TEXTAREA element

Property Description
Asp-for Name of the Model field

span element

Property Description
Asp-validation-for Name of the Model field

div element

Property Description
Asp-validation-aummary ValidationSummary enumeration value:
Validationsummary.all
Validationsummary.modelonly
Validationsummary.none.

Verify the description type and only Validationsummary.all and Validationsummary.modelonly are selected to render the DIV element.

Select element

Property Description
Asp-for Model Field Name
Asp-items Model Field Name

LINK element

Property Description
Asp-href-include
Asp-href-exclude
Asp-fallback-href Alternate address when default href load fails
Asp-fallback-href-include
Asp-fallback-href-exclude
Asp-fallback-test-class To determine the class style to use when loading fails
Asp-fallback-test-property To determine the attributes in the class style used when loading fails
Asp-fallback-test-value To determine the value of a property in the class style used when the load fails
Asp-file-version
Href The default loaded CSS file address.

The use of link is shown below, for example, we define the following code:

<link rel= "stylesheet" 
href= "//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/ Bootstrap-touch-carousel.css "
asp-fallback-href=" ~/lib/bootstrap-touch-carousel/css/ Bootstrap-touch-carousel.css "
asp-fallback-test-class=" carousel-caption " 
asp-fallback-test-property=" Display " 
asp-fallback-test-value=" None "/>"

Then the code indicates that the default first load aspnetcdn.com on the CSS file, if the load failed, and then load the local Web site CSS file, load failure to determine the condition is: detection carousel-caption style is very applied, that is the application of the style of the elements of the display attribute is equal to none. After running the Web site, this code generates HTML as follows:

<link rel= "stylesheet" href= "//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/ Bootstrap-touch-carousel.css "/> <meta name= x-stylesheet-fallback-test" class= "carousel-caption"/>
<script>
 !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 (' <link rel= ' stylesheet ' href= ' + C [d] + '/> '}}
 ("Display", "none", ["\/lib\/bootstrap-touch-carousel\/css\/ Bootstrap-touch-carousel.css "]);
</script>

From this, we see that the generated HTML code has two more elements after the link element, one with class="carousel-caption" attributes and one with script script tags. The main principles are as follows:

Apply the defined style to the META element carousel-caption . Detects whether the META element's display properties are equal to or not through JS code none . If not equal none , reload the local alternate CSS file.

Note that the JS script here is used to get the element in the form of the document.getElementsByTagName("SCRIPT") last sibling element of the final SCRIPT tag meta .

Script element

Property Description
Asp-src-include
Asp-src-exclude
Asp-fallback-src Alternate JS file address
Asp-fallback-src-include
Asp-fallback-src-exclude
Asp-fallback-test Determine if the default JS file is loaded with the successful object
Asp-file-version
Src The default JS file address.

scriptTag elements of the fallback function, and link element record CSS file type, but here is not Judge class style, but to detect the existence of an object, to determine whether the default JS file loading success, examples are as follows:

<script src= "//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js"
 asp-fallback-src= "~/lib/jquery/ Jquery.min.js "
 asp-fallback-test=" Window.jquery ">
</script>

The generated HTML code, which is relatively simple, is the following example:

<script src= "//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js" >
</script>
<script > (window.jquery| | document.write ("<script src=\" \/lib\/jquery\/jquery.min.js\ "><\/script>"));</script>

Generate more than one script tag element, and then determine whether the jquery object exists, if it does not exist to indicate that the load failed, then load the local standby JS file.

Cache

Property Description
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 .

Using Environmenttaghelper to control the output of different operating environments

In many cases, we want to use a set of configuration information in the development environment, and in a different set of production environments, we need to use conditional judgment statements, but in the new version of MVC, using the environment element tag provided by Environmenttaghelper is OK, Examples are as follows:

<environment names= "Development" > <script src= "~/lib/jquery/jquery.js" ></script> <script src= " ~/lib/bootstrap/js/bootstrap.js "></script> <script src=" ~/lib/hammer.js/hammer.js "></script > <script src= "~/lib/bootstrap-touch-carousel/js/bootstrap-touch-carousel.js" ></script> </ environment> <environment names= "staging,production" > <script src= "//ajax.aspnetcdn.com/ajax/jquery/ Jquery-1.10.2.min.js "asp-fallback-src=" ~/lib/jquery/jquery.min.js "asp-fallback-test=" Window.jQuery "> </ script> <script src= "//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/bootstrap.min.js" asp-fallback-src= "~/lib/" Bootstrap/js/bootstrap.min.js "asp-fallback-test=" Window.jquery "> </script> <script src="/
   Ajax.aspnetcdn.com/ajax/hammer.js/2.0.4/hammer.min.js "asp-fallback-src=" ~/lib/hammer.js/hammer.js " asp-fallback-test= "window. Hammer "> </script> <script src="//ajax.aspnetcdn.com/ajax/bootsTrap-touch-carousel/0.8.0/js/bootstrap-touch-carousel.js "asp-fallback-src=" ~/lib/bootstrap-touch-carousel/js/ Bootstrap-touch-carousel.js "asp-fallback-test=" window. Zepto "> </script> </environment>

In the above code, we set, if it is development environment to use the local JS file, otherwise (staging or production environment) first load CDN's file (but still have a backup plan).

The values in the names are judged by the attributes that are found, compared with them, and IHostingEnvironment EnvironmentName then processed accordingly.

Custom Taghelper

MVC all Taghelper implementations inherit the Microsoft.AspNet.Razor.Runtime.TagHelpers.ITagHelper interface, so we can implement the custom taghelper as long as we implement the interface, which is defined as follows:

Public interface Itaghelper
{
 int order {get;}
 Task Processasync (taghelpercontext context, taghelperoutput output);
}

However, when we customize it, we just need to inherit the default implementation class of the interface TagHelper and overload its virtual method Process methods, as follows are a few examples, let's look at it in more detail.

1. Support Controller and action attributes directly on the A element

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 && Amp Action!= null)
  {
   var methodparameters = output. Attributes.todictionary (attribute => attribute. Key,
                 attribute => (object) attribute. Value);

   Deletes all attributes because output is already generated automatically in the route
   . Attributes.clear ();

   Output. attributes["href"] = urlhelper.action (Action, Controller, methodparameters);

   Output. Precontent.setcontent ("my");}}

2. Automatically identify the link in the text and extract it

[Targetelement ("P")]
public class Autolinkertaghelper:taghelper
{public
 override async Task Processasync (Taghelpercontext context , taghelperoutput Output)
 {
  var childcontent = await context. Getchildcontentasync ();

  Find URL in the content and replace them with their anchor tag equivalent.
  Output. Content.setcontent (Regex.Replace (
   childcontent.getcontent),
   @ "\b (?: https?:/ /|www\.) (\s+) \b ",
   " <strong><a target=\ "_blank\" href=\ "http://$0\" >$0</a></strong> "));
 }

3. Conditional judgment

Defines a condiction that displays the element if it is eligible, as shown below (this element is displayed only if model.approved is true):

<p condition= "model.approved" >© @Model. copyrightyear-my asp.net application</p>

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 &&!) is not rendered. Condition.value)
  {
   output. Suppressoutput ();}}

4. Taghelper of custom elements

If we want to define taghelper for the custom element, we want to conform to the Convention specification, as the sample code reads 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 (
   "<p><strong>Version:</strong> {0}</p>" + Environment.NewLine +
   ) <p> <strong>copyright year:</strong> {1}</p> "+ Environment.NewLine +
   " <p><strong> approved:</strong> {2}</p> "+ Environment.NewLine +
   " <p><strong>number of tags to show: </strong> {3}</p> "+ Environment.NewLine,
   Info.Version.ToString (),
   Info.CopyrightYear.ToString (), Info.Approved.ToString (), Info.TagsToShow.ToString ())
   ;
  Output. Selfclosing = false;
 }
}

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

<website-information info= "New Websitecontext {
        Version = new version (1, 1),
        copyrightyear = 1990,
        Approved = True,
        tagstoshow =} "/>

The rendering result is rendered as an p element that contains 4 elements section .

Related Article

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.