Thursday 5 May 2016

How to use tag helpers in ASP.NET MVC

in this post I want to show you how to use tag helpers in ASP.NET MVC 6.

First of all: What are the tag helpers good for?
If you are coding your links in your MVC-Views with normal strings its really hard to refactor or correct them in case you rename your routing, controller or your action. So you need a kind of generic approach to do this.
Razor in previous versions had this
which returned an url like “MyController/MyAction/123”
MVC 6 is now introducing a new more readable way to achieve the same result called TagHelpers.
If you are using the normal MVC6-Template from Visual Studio asp-net TagHelpers are already included! However, I will mention the necessary steps anyway.
Getting started:
First make sure you included a reference to the tag helpers in your project.json
TagHelpers_1
And Because tag helpers do not throw an exception if you use them and they do not work you should also include a _ViewImports.cshtml which is responsible to load all extra functionality to your views. You can simply add it via the context menu Add –> New Item.
TagHelpers_2TagHelpers_3
Now all the cshtml files are able to handle Asp.Net-TagHelpers which get easily in your html like this:
which is rendered to
That is great because you do not have to use a non-html-syntax anymore and it it easier to understand and to read.
You can also write forms in this Html-Tag-Helper-Syntax which is really nice to understand
instead of using the “ugly” @-like Sytax before.

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...