diff --git a/aspnetcore/mvc/views/tag-helpers/builtin.md b/aspnetcore/mvc/views/tag-helpers/builtin.md index 9097c27c41bb..1a63ff8061e6 100644 --- a/aspnetcore/mvc/views/tag-helpers/builtin.md +++ b/aspnetcore/mvc/views/tag-helpers/builtin.md @@ -2,16 +2,16 @@ By [Peter Kellner](http://peterkellner.net) -Microsoft has included 17 Tag Helpers that can be immediately used in .net Core web projects. These Tag Helpers are complete and production quality and are recommended to be used in projects where appropriate. In this section we will outline all the built in Tag Helpers along with a sample of each tag helper in use. +Microsoft has included multiple Tag Helpers that can be immediately used in .net Core web projects. These Tag Helpers are complete and production quality and are recommended to be used in projects where appropriate. In this section we will outline all the built in Tag Helpers along with a sample of each tag helper in use. > [!NOTE] > There are other Tag Helpers built in that are not discussed as they are used internally in the Razor view engine. This includes a tag helper for the ~ character which expands to the root path of the web site (among others). ## Built in ASP.NET Core Tag Helpers -**[AnchorTagHelper](builtin/resources/AnchorTagHelper.md)** +**[Anchor Tag Helper](builtin/resources/AnchorTagHelper.md)** -[comment]: **[CacheTagHelper](builtin/resources/AnchorTagHelper.md)** +**[Cache Tag Helper](builtin/resources/CacheTagHelper.md)** [comment]: **[DistributedTagHelper](builtin/resources/AnchorTagHelper.md)** @@ -21,7 +21,7 @@ Microsoft has included 17 Tag Helpers that can be immediately used in .net Core [comment]: **[FormTagTagHelper](builtin/resources/FormTagHelper.md)** -[comment]: **[ImageTagHelper](builtin/resources/ImageTagHelper.md)** +**[Image Tag Helper](builtin/resources/ImageTagHelper.md)** [comment]: **[InputTagHelper](builtin/resources/InputTagHelper.md)** @@ -39,9 +39,9 @@ Microsoft has included 17 Tag Helpers that can be immediately used in .net Core [comment]: **[ValidationMessageTagHelper](builtin/resources/ValidationMessageTagHelper.md)** -[comment]: **[ValidationSummaryHelper](builtin/resources/ValidationSummaryTagHelper.md)** - -
+[comment]: **[ValidationSummaryTagHelper](builtin/resources/ValidationSummaryTagHelper.md)** + + ## Additional Resources diff --git a/aspnetcore/mvc/views/tag-helpers/builtin/resources/AnchorTagHelper.md b/aspnetcore/mvc/views/tag-helpers/builtin/resources/AnchorTagHelper.md index 395b5a585716..679e22edcb95 100644 --- a/aspnetcore/mvc/views/tag-helpers/builtin/resources/AnchorTagHelper.md +++ b/aspnetcore/mvc/views/tag-helpers/builtin/resources/AnchorTagHelper.md @@ -1,74 +1,72 @@ [Back To Built In Tag Helpers List](../../builtin.md) -# AnchorTagHelper +# Anchor Tag Helper By [Peter Kellner](http://peterkellner.net) -The ```AnchorTagHelper``` enhances the html anchor (``) tag. A new set of attributes are defined that work with the anchor tag. The link generated (on the href tag) is based on a combination of these new attributes that work together to form the final redirect URL. That URL can include an optional protocol such as https. +The Anchor Tag Helper enhances the html anchor (``) tag. A new set of attributes are defined that work with the anchor tag. The link generated (on the `href` tag) is based on a combination of these new attributes that work together to form the final URL. That URL can include an optional protocol such as https. -For reference, the following ASP.NET ```startup.cs``` and ```SpeakerController.cs``` are defined as you would expect in a default Visual Studio .Net Core Web Project. - -![](../_static/ProjectControllers.png) - -**Startup.cs** -``` -// This method gets called by the runtime. -// Use this method to configure the -// HTTP request pipeline. -public void Configure(IApplicationBuilder app, - IHostingEnvironment env, - ILoggerFactory loggerFactory) -{ - app.UseMvcWithDefaultRoute(); - //... -} -``` +The speaker controller used in attribute definitions below is shown here.
**SpeakerController.cs** [!code-csharp[SpeakerController](../sample/TagHelpersBuiltInAspNetCore/src/TagHelpersBuiltInAspNetCore/Controllers/SpeakerController.cs)] -
-These attributes are defined as follows: -## asp-controller +## Anchor Tag Helper Attributes + +- - - -```asp-controller``` is used to associate which controller will be used to generate the final URL. The only valid choices are controllers that exist in the current project. In our case, to get to a list of all speakers or speaker details you would specify ```asp-controller="Speaker"```. If you only specify ```asp-controller``` and no ```asp-action``` the URL will generate without an error but will likely not be what you expect. +### asp-controller -## asp-action +`asp-controller` is used to associate which controller will be used to generate the final URL. The only valid choices are controllers that exist in the current project. To get to a list of all speakers specifying `asp-controller="Speaker"` is required. If only the `asp-controller` and no `asp-action` is specified, the default asp-action will be the name of the the controller method calling this view page. -```asp-action``` is the name of the method in the controller that will be included in the final URL. That is, in the example, if the route to the Speaker Detail page is wanted, then the attribute should be set to ```asp-action=Detail```. You should always set ```asp-controller``` when specifying ```asp-action```. If no ```asp-action``` is specified then a URL will generate without an error but will likely not be what you expect. +- - - + +### asp-action -## asp-route- +`asp-action` is the name of the method in the controller that will be included in the final URL. That is, in the example, if the route to the Speaker Detail page is wanted, then the attribute should be set to `asp-action=Detail`. You should always set `asp-controller` when specifying `asp-action`. If no `asp-action` is specified then the default `asp-controller` will be the current executing controller. -```asp-route-``` is basically a wild card route prefix. Any value you put after the trailing dash will be interpreted as the parameter to pass into the route. For example, if you create a tag as follows: +- - - + +### asp-route-{value} -```Speaker 11``` +`asp-route-` is a wild card route prefix. Any value you put after the trailing dash will be interpreted as the parameter to pass into the route. For example, if a tag is created as follows: -the href generated will be +`Speaker 11` -```Speaker 11``` +the `href` generated will be + +`Speaker 11` This is because a route was found that matched a single parameter "id" in the ```SpeakerController``` method ```Detail```. If there was no parameter match, say for example you created the tag helper -```Ronald``` +`Ronald` you would get generated the html -```Ronald``` +`Ronald` + +This is because there was no route found that matched a controller that had a method named `Detail` with one string parameter titled `name`. -This is because there was no route found that matched a controller that had a method named ```Detail``` with one string parameter titled ```name```. +- - - -## asp-route +### asp-route -```asp-route``` provides a way to create a URL that links directly to a named route. Using routing attributes, you can name your routes as shown in the Evaluations method above of the ```SpeakerController```. ```Name = "speakerevals"``` tells the AnchorTagHelper to generate a route directly to that controller method using the URL ```/Speaker/Evaluations```. If ```asp-controller``` or ```asp-action``` is specified in addition to ```asp-route``` then the route generated will not be what you expect. ```asp-route``` should not be used with either of the attributes ```asp-controller``` or ```asp-action``` to avoid a route conflict. +`asp-route` provides a way to create a URL that links directly to a named route. Using routing attributes, a route can be named as shown in the `SpeakerController` and used in its `Evaluations` method. -## asp-all-route-data +`Name = "speakerevals"` tells the Anchor Tag Helper to generate a route directly to that controller method using the URL `/Speaker/Evaluations`. If `asp-controller` or `asp-action` is specified in addition to `asp-route`, the route generated may not be what you expect. `asp-route` should not be used with either of the attributes `asp-controller` or `asp-action` to avoid a route conflict. -```asp-all-route-data``` allows you to create on your current .net context (that is, the running c# associated with your razor page) a dictionary of key value pairs where the key is the parameter name and the value is the value associated with that key. As the example below shows, you can create an inline dictionary on your razor page and then create the ```AnchorTagHelper``` right after that. You could of course pass in the dictionary with your model or as your model. That avoids having extra c# code on your razor page and gives you better control of the data passed to your view. +- - - + +### asp-all-route-data + +`asp-all-route-data` allows creating on a .NET context (that is, the running C# associated with your Razor view) a dictionary of key value pairs where the key is the parameter name and the value is the value associated with that key. + +As the example below shows, an inline dictionary is created and the data is passed to the razor view. The data could also be passed in with your model to keep the Razor view simpler. ``` @{ @@ -89,33 +87,59 @@ The code that this generates looks as follows: http://localhost/Speaker/EvaluationsCurrent?speakerId=11¤tYear=true ``` -When the link is clicked, this will call the controller method ```EvaluationsCurrent``` because that controller has two string parameters that match what has been created from the ``` -asp-all-route-data``` -dictionary. +When the link is clicked, this will call the controller method `EvaluationsCurrent` because that controller has two string parameters that match what has been created from the `asp-all-route-data` dictionary. + +- - - -## asp-fragment +### asp-fragment -```asp-fragment``` appends after a hash (```#```) tag at the end of the URL whatever the value assigned to it is. That is, if you create a tag +`asp-fragment` defines a URL fragment to append to the URL. The Anchor Tag Helper will add the hash character (#) automatically. If you create a tag: ``` About Speaker Evals ``` + The generated URL will be + ``` http://localhost/Speaker/Evaluations#SpeakerEvaluations ``` + Hash tags are useful when doing client side applications. They can be used for easy marking and searching in JavaScript for example. +- - - -## asp-area +### asp-area -```asp-area``` allows for a razor view area to be associated with the hyperlink URL. That is, if you have a project setup in a similar fashion to the project pictured below, the link generated will include as its first segment the area you mention. +`asp-area` sets the area name that ASP.NET Core uses to set the appropriate route. Below are examples of how the area attribute causes a remapping of routes. Setting `asp-area` to Blogs prefixes the directory Areas/Blogs to the routes of the associated controllers and views for this anchor tag.. -![](../_static/ProjectControllersArea.png) +* Project name -Specifying an area tag that is valid, such as ```area="Blogs"``` when referencing the ```AboutBlog.cshtml``` file will look like the following using the ```AnchorTagHelper```. + * *wwwroot* + + * *Areas* + + * *Blogs* + + * *Controllers* + + * *HomeController.cs* + + * *Views* + + * *Home* + + * *Index.cshtml* + + * *AboutBlog.cshtml* + + * *Controllers* + + + +Specifying an area tag that is valid, such as ```area="Blogs"``` when referencing the ```AboutBlog.cshtml``` file will look like the following using the Anchor Tag Helper. ``` Blogs About @@ -128,13 +152,13 @@ The generated HTML will include the areas segment and will be as follows: ``` > [!TIP] -> For MVC Areas to work in your web application, the route template must include a reference to the area if it exists. That template (which is the second parameter of the ```routes.MapRoute``` method call) will look as follows: ```template: "{area:exists}/{controller=Home}/{action=Index}"```. - +> For MVC areas to work in a web application, the route template must include a reference to the area if it exists. That template, which is the second parameter of the `routes.MapRoute` method call, will appear as: template: '"{area:exists}/{controller=Home}/{action=Index}"' +- - - -## asp-protocol +### asp-protocol -The ```asp-protocol``` is for specifying a particular protocol (such as ```https```) in your URL. An example ```AnchorTagHelper``` that includes the protocol will look as follows. +The `asp-protocol` is for specifying a particular protocol (such as `https`) in your URL. An example Anchor Tag Helper that includes the protocol will look as follows. ```About``` @@ -142,6 +166,14 @@ and will generate HTML as follows. ```About``` -(of course the domain, in the case above is localhost, but this will be substituted for whatever the actual domain hosting the web site is hosted at). +The domain in the example is localhost, but the Anchor Tag Helper uses the website's public domain when generating the URL. + +- - - + +## Additional Resources + +* [Areas](../../../../controllers/areas.md) + + diff --git a/aspnetcore/mvc/views/tag-helpers/builtin/resources/CacheTagHelper.md b/aspnetcore/mvc/views/tag-helpers/builtin/resources/CacheTagHelper.md new file mode 100644 index 000000000000..a666b9ebc796 --- /dev/null +++ b/aspnetcore/mvc/views/tag-helpers/builtin/resources/CacheTagHelper.md @@ -0,0 +1,286 @@ +[Back To Built In Tag Helpers List](../../builtin.md) + +# Cache Tag Helper + +By [Peter Kellner](http://peterkellner.net) + + +The Cache Tag Helper provides the ability to dramatically improve the performance of your ASP.NET Core app by caching its content to the internal ASP.NET Core cache provider. + +A simple example that shows the Cache Tag Helper in action sets the current time in its content area. The Razor View Engine sets the default `expires-after` to twenty minutes, which is the default if you specify no additional attributes. + +Here is an example of the code you include in your `cshtml` page to achieve the default cache behavior described above. + +```html +@DateTime.Now +``` + +If you repeatedly refresh the page that contains `CacheTagHelper`, the first time the current`DateTime`will be shown. Repeated refreshes of the page will continue to show the first `DateTime` shown until the cache expires (which is likely to be twenty minutes unless server memory pressure evicts the cache sooner). + +You can achieve more control of the cache duration of the content by setting any of the following attributes: + +## Cache Tag Helper Attributes + +- - - + +### enabled + + +| Attribute Type | Valid Values | +|---------------- |---------------- | +| boolean | "true" (default) | +| | "false" | + + +The attribute `enabled` determines whether any caching is performed of the content inside the Cache Tag Helper. The default is `true`, which results in all other attributes being valid. The default value is `true`. If set to `false`, regardless of what other attributes are specified, this Cache Tag Helper will have no caching effect on the rendered output. +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### expires-on + +| Attribute Type | Example Value | +|---------------- |---------------- | +| DateTimeOffset | "@new DateTime(2025,1,29,17,02,0)" | + + +The attribute `expires-on` sets a deterministic expiration date for caching the content of the Cache Tag Helper when it is first rendered. The example below will cache the contents of the Cache Tag Helper until 5:02 PM on January 29, 2025. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### expires-after + +| Attribute Type | Example Value | +|---------------- |---------------- | +| TimeSpan | "@TimeSpan.FromSeconds(120)" | + + +The attribute `expires-after` sets a specific amount of time from the current `DateTime` to cache the contents of the Cache Tag Helper. This value is set when it is first rendered. The example below caches the contents of the Cache Tag Helper for one hundred twenty seconds. If there is memory pressure on the server, the cache may be evicted sooner. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### expires-sliding + +| Attribute Type | Example Value | +|---------------- |---------------- | +| TimeSpan | "@TimeSpan.FromSeconds(5)" | + + +The attribute `expires-after` sets a specific amount of time from the current `DateTime` that the contents of the `Cache` tag helper will be kept in cache. This value is set when the `Cache` tag helper is first rendered. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### vary-by-header + +| Attribute Type | Example Values | +|---------------- |---------------- | +| String | "User-Agent" | +| | "User-Agent,content-encoding" | + +The attribute `vary-by-header` accepts a single header value or a comma-separated list of header values that trigger a cache refresh when they change. The example below looks at the header value `User-Agent`, which will cache the content for every different `User-Agent` presented to the web server. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### vary-by-query + +| Attribute Type | Example Values | +|---------------- |---------------- | +| String | "Make" | +| | "Make,Model" | + +The attribute `vary-by-query` accepts a single header value or a comma-separated list of header values that trigger a cache refresh when they change. The example below looks at the values of `Make` and `Model`; and when either or both change, the content of the Cache Tag Helper is rendered again, and the cache is reset. + +Usage Example: + +``` +html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### vary-by-route + +| Attribute Type | Example Values | +|---------------- |---------------- | +| String | "Make" | +| | "Make,Model" | + +The attribute `vary-by-route` accepts a single header value or a comma-separated list of header values that trigger a cache refresh when they change. The example below looks at the values of `Make` and `Model`. When either or both change, the content of the Cache Tag Helper is rendered again, and the cache is reset. + +Usage Example: + +*Startup.cs* + +```csharp +routes.MapRoute( + name: "default", + template: "{controller=Home}/{action=Index}/{Make?}/{Model?}"); +``` + +*Index.cshtml* + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### vary-by-cookie + +| Attribute Type | Example Values | +|---------------- |---------------- | +| String | ".AspNetCore.Identity.Application" | +| | ".AspNetCore.Identity.Application,HairColor" | + +The attribute `vary-by-cookie` accepts a single header value or a comma-separated list of header values that trigger a cache refresh when they change. The example below looks at the cookie associated with asp.net Identity. When a user is authenticated causing the request cookie to be set, The content of the Cache Tag Helper is rendered again, and the cache is reset. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +```` + +- - - + +### vary-by-user + +| Attribute Type | Example Values | +|---------------- |---------------- | +| Boolean | "true" | +| | "false" (default) | + +The attribute `vary-by-user` specifies whether or not the cache should reset when the logged-in user (or Context Principal) changes. The current user is also known as the Request Context Principal and can be viewed in a Razor view by referencing `@User.Identity.Name`. + +The example below looks at the current logged in user. When a different user is found, The content of the Cache Tag Helper is rendered again, and the cache is reset. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +> [!NOTE] +> Using the attribute `vary-by-user` maintains the contents in cache through a log-in and log-out cycle. When using `vary-by-cookie` which references the `.AspNetCore.Identity.Application` as shown above, a log-in and log-out action invalidates the cache for the same authenticated user because a new cookie value is generated. If no user is authenticated, that state is considered a valid cache state, which means that no logged-in user is one cache state, and the contents will be maintained for that condition as well. + +- - - + +### vary-by + +| Attribute Type | Example Values | +|---------------- |---------------- | +| String | "@Model" | + + +The attribute `vary-by` allows for customization of what data gets cached. When the object referenced by the attribute's string value changes, the content of the Cache Tag Helper is updated. Often a string-concatenation of model values are assigned to this attribute. Effectively, that means any update to any of the concatenated values invalidates the cache. + +The example below assumes the controller method rendering the view sums the integer value of the two route parameters, `myParam1` and `myParam2`, and returns that as the single model property. When this sum changes, the content of the Cache Tag Helper is rendered again, and the cache is reset. + +Usage Example: + + +*Controller* + +```csharp +public IActionResult Index(string myParam1,string myParam2,string myParam3) +{ + int num1; + int num2; + int.TryParse(myParam1, out num1); + int.TryParse(myParam2, out num2); + return View(viewName, num1 + num2); +} +``` + +*Index.cshtml* + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +- - - + +### priority + +| Attribute Type | Example Values | +|---------------- |---------------- | +| CacheItemPriority | "High" | +| | "Low" | +| | "NeverRemove" | +| | "Normal" | + +The attribute `priority` provides cache ejection guidance to the built-in cache provider. If the web server experiences memory pressure and evicts one or more of your cached entities, it will evict Low priority cache entities first. + +Usage Example: + +```html + + Current Time Inside Cache Tag Helper: @DateTime.Now + +``` + +> [!WARNING] +> using the `priority` attribute does not guarantee any specific level of cache retention. It is simply a suggestion to the Cache Provider. To be extra clear, setting this attribute to `NeverRemove` does not guarantee that the cache will not be evicted. More details can be found in the additional resources listed below. + +- - - + + +>[!NOTE] +> The Cache Tag Helper is dependent on the built in Memory Cache service being included in the `startup.cs` ConfigureServices method. Adding this service is not necessary because the built in Tag Helper extensions take care of this in the `AddMvc` method call. + +## Additional Resources + +* +* + + + + diff --git a/aspnetcore/mvc/views/tag-helpers/builtin/resources/ImageTagHelper.md b/aspnetcore/mvc/views/tag-helpers/builtin/resources/ImageTagHelper.md new file mode 100644 index 000000000000..0f0621ec6b89 --- /dev/null +++ b/aspnetcore/mvc/views/tag-helpers/builtin/resources/ImageTagHelper.md @@ -0,0 +1,50 @@ +[Back To Built In Tag Helpers List](../../builtin.md) + +# ImageTagHelper + +By [Peter Kellner](http://peterkellner.net) + +The Image Tag Helper enhances the `img` (``) tag. It requires a `src` tag as well as the `boolean` attribute `asp-append-version`. + +If the image source (`src`) is a static file on the host web server, a unique cache busting string is appended as a query parameter to the image source. This insures that if the file on the host web server changes, a unique request URL is generated that includes the updated request parameter. The cache busting string is a unique value representing the `SHA256` hash of the static image file. + +If the image source (`src`) isn't a static file, possibly a remote URL or the file doesn't exist on the server, the `` tag's `src` attribute is generated with no cache busting query string parameter. + +## Image Tag Helper Attributes + +- - - + +### asp-append-version + +`asp-append-version` is the only attribute available for the Image Tag Helper. When specified along with a `src` attribute, this Image Tag Helper is invoked. + +An example of a valid `img` tag helper is: + +```html + +``` + +If the static file exists on the web server, typically in the directory `..wwwroot/images/asplogo.png` the generated html is: + +```html + +``` + +The value assigned to the parameter `v` is the hash value of the file on disk generated using the .NET library method `CryptographyAlgorithms.CreateSHA256().ComputeHash()`. If the web server is unable to obtain read access to the static file referenced, `wwwroot/images/asplogo.png`, no `v` parameters is added to the `src` attribute, and the original src attribute is unchanged. + +- - - + +### src + +To activate the Image Tag Helper, the src attribute is required on the `` element. + +> [!NOTE] +> The Image Tag Helper uses the `Cache` provider on the local web server to store the calculated `Sha512` of a given file. If the file is requested again the `Sha512` does not need to be recalculated. The Cache is invalidated by a file watcher that is attached to the file when the file's `Sha512` is calculated. + +## Additional Resource + +* + +