Web Hack Wednesday

Tag Helpers in ASP.Net Core

Rate this post
(Video Transcript)
Hello and welcome to Web Hack Wednesday.

>> I’m Martin Beeby.

>> And I’m Martin Kearn.

>> And today we’re going to be talking about-

>> ASP.NET tag helpers.

>> ASP.NET tag helpers.

>> Yes.

>> Which are a new Razor feature. So if you’re an MVC person doing ASP.NET stuff, you know what Razor is. This is the new edition to Razor which we can find inside of ASP.NET Core.

>> Yeah, and they’re really cool. They sort of make life a bit easier. Really, the main thing is, they make your code pretty, like prettier to look at.

>> Well, yeah, I find the-

>> And they color in your code, as well.

>> So instead of using HTML helpers is that the name?

>> Yep that’s right yeah.

>> Which require you to do this quite strange sort of escaping.

>> Yeah.

>> Well not strange but.

>> It is quite strange yeah.

>> But it’s one of the benefits of Razor that you can do this escaping.

>> Yeah.

>> To escape into a mix. HTML and C# code.

>> Absolutely, yeah.

>> But when you’re having to do that just to make forms or existing this due, or create HTML elements.

>> Yeah.

>> This actually seems like quite a difficult way of doing that.

>> Is that right? Yeah.

>> HTML helpers.

>> And there are other problems as well. So one thing about tag helpers is it makes your markup very standard looking, so it looks like standard HTML markup.

>> Yeah.

>> Which is great, cuz if you give it to a designer or front end dev that’s not necessarily an ASP.NET person, they’re gonna just be able to work with that. Whereas if you give them the 4.X style of HTML helpers, they won’t know what that is, necessarily. And it’ll look strange and confusing. But people will buy it.

>> Okay, it’s quite a difficult concept to describe, so should we switch over to computer and show it?

>> Let’s do that, yeah. So just to start off with, this is a ASP.NET core project which I’ve created just using the standard web application template. And I’ve actually scaffolded out a controller, people controller, with the views as well. So if we just take a look at the create view, so this is just a standard code that you get if you scaffold something out. And you’ll see, you might have notice just there on the video, initially that was just blue and it turn to green. So, the form tags and the div and the labels and input and spans, that turn to this nice, I guess it’s It’s a teal color.

>> I was gonna say teal.

>> Yeah, yeah.

>> Yeah, I think it’s teal, we’ll call it teal or just green but it’s not blue, that’s the main thing. And what that means is basically those are tag helpers. If it turns teal then you know it’s a tag helper, but it looks and feels like a regular HTML tag which is one of the great things about it.

>> Yeah.

>> And you’ll see that they’re decorated to these asp attributes. So you can see on the form there we’ve got asp-action and on the div you have asp-validationSummary.

>> Just one thing, so you can add attributes to existing HTML elements like div.

>> Yeah.

>> And form.

>> Yeah.

>> And instance.

>> But you can also create as well.

>> There’s actually three types of tag helper that you can have. One is, like you say, you can enhance existing standard elements. So in this case the form has been enhanced by asp-action, so I’ve added some extra stuff to the form. asp-action just says which action it submits to. If I just zoom back out here, you can also have a whole new element. So if I go to the layout page here, you’ve got a thing called an environment tag helper for this guy here. So this is a whole new tag helper called environment that does things around, and it looks at the environmental variable to see whether it’s in dev mode or staging or production. And it will do different things based on that. So that’s where that’s been invented as a tag helper. And the third thing is where you can just have a tag helper that’s basically doesn’t really have any output. It just does something. So yeah, an environment is a good example of that.

>> Right, cuz you mean environment’s not a new tag that you’re creating which is actually gonna be output to the browser.

>> No, that’s it.

>> It’s basically like between the HTML.

>> Exactly, yeah.

>> So if you’re in a development environment, it’s gonna put that link and that link in there. And if it’s in staging and production, it’s gonna have different links in there. But the environment tag that you’re creating is not really generating any output.

>> No, the output will just be a set of link tags. But they’ll will differentiate between these two. It is like an if-then statement basically, yeah.

>> But you could equally be outputting an actual tag.

>> Yes, you could. Yeah,

>> And so link’s another good example here. So we’ve got, if you look at top at where it says Development, those are just standard links. So the idea here is if you’re in development mode you can use local copies of Bootstrap and our local style sheets. If you look at the next bit down where it says Staging,Production, we’ve got these, there again they’re decorated so our asp-fallback-href, asp-fallback-test-class, there’s a lot of intelligence in the link tag helper. So it will fall back and gracefully fail, and try other things if the main thing isn’t available. So, in this particular case, it will try and get a Bootstrap from the ASP.NET CDN. If that’s not there it fell back to the local minified version basically. So it’s a nice intelligence built into that. Another thing we’ve got we can point out with link is we’ve got the append version. This gets around quite a common problem around caching, browser caching. It means it will append the version and will automatically when it changes.

So it’s just. The idea is you’ve got the server-side intelligence and being able to bring that into your html and your markup really easily and really simply using the standards.

>> To be clear, the thing that gets output to the browser. In this example of a link tag here.

>> Yeah.

>> That’s not gonna contain-

>> Well that’s-

>> The word asp-append.

>> Yeah, well let’s take a look at that. Let’s just run the sentence. So this is, we’ve got a layout page with all this stuff in here. We’ve got a similar set of environment text for our JavaScript at the bottom. And then if we just take a look at just the home page for the whole site here. I’ll get to the create page so if we just run this so we can exactly what the markup looks like. [INAUDIBLE] markup because tag helpers are a development thing. They’re not necessary gonna affect the markup, they’re just gonna affect the development experience.

>> Right.

>> So if we just go to slash people and create a new person. That’s not good. Okay I’ll just gonna do that quickly. [LAUGH]

>> What that say?

>> Identify work component that haven’t uploaded migrations. But it’s really good cuz it.

>> I’ve never seen that screen though.

>> It’s gives you a button to press.

>> Okay, we’re gonna back up a little bit here.

>> Just pretend that didn’t happen.

>> We’ll pretend that didn’t happen, yeah.

>> I’m not gonna cut it, I’m too lazy.

>> Really, okay, anyway. This is the page that’s rendered and if we just do the F12 on this. We just go here and do developer tools and actually take a look at the markup. If we just say look at that there, so this is just rendering standard labels. If we look at all the CSS stuff up in the head, so will all those environment tags. Well it’s actually been rendered from all of those environments. How it’s those two links there.

>> Yeah.

>> And again, if we look down at the JavaScript at the bottom, the thing that’s rendered is a bunch of script tags.

>> Where’s was that one which had the append version on it?

>> I’m not sure. It’s the site.js.

>> Site.js?

>> Yes.

>> All right, so it’s just adding some randomness to it?

>> So it’s just adding, yeah, randomness is probably the best way to describe it. It’s not a gui it’s just some random stuff.

>> Right okay.

>> I’m sure it probably is a thing but it’s a-

>> So that’s another thing, so that’s only ever been updated if we’ve made a change right there?

>> Exactly yeah so if we change our file then it’s gonna generate a new one of those random strings and browsers with mv cache the file.

>> I think they call that a cache busting.

>> Cache busting yes, yes.

>> Cache busting. Strategy.

>> Strategy, yes.

>> In fact, I think Madge Christiansen’s got a blog article about exactly this technique.

>> Okay.

>> I think he calls it cache busting. It’s really hard to say that.

>> Cache busting strategy.

>> Yeah. Anyway, so that’s-

>> Everyone needs a cache busting strategy.

>> They do, yeah. If you’re caching and you need to bust cache, then you need to have a cache busting strategy.

>> Well, if you get through a certain period in your life then ultimately there will come a time when you need a cache busting strategy.

>> Yeah, especially if your in the world of soft-

>> Have you got a strategy? What, a cache busting strategy?

>> Yeah I’ve got one of those, I’m using these tag helpers to help me out a bit. So that’s tag helper as they are. Now if we just contrast that to 4.5, so I’ve got exactly the same project set up in the exactly the same way with .net 4.5, 4.5.2 to be precise, but that doesn’t matter. We look at the same page, so I’ve used the same model to scaffold this, so we just compare that to what we’ve got here, so. It’s effectively doing the same thing but we are using the old style HTML helpers here and look how messy and horrible that looks compared to the tag helpers. So if we just take this one as an example, this label here. So this, all this generate is a label, okay, a label with CSS class of control label and col md 2 on there.

>> That’s all it does, and yet we’ve got quite a lot of code there.

>> Yeah.

>> And then if we contrast that to the tag helper way of doing it, which is, I had to stop there a minute. The exact same label in tag helpers in this guy here. So it’s much more simple. A designer would be able to look at that and say, I know what that is it’s HTML.

>> Yeah, yeah.

>> So, that’s what they’re all about, and these, obviously, is lead built in tag helpers. Which is most of the HTML form type elements, especially, our influences tag helpers, you can just add things to help you out with.

>> I think if you go into view imports in this HTML file.

>> Yes.

>> If you look into view imports, is it that one?

>> Yes.

>> So it’s in import. I’m glad you brought that up actually, because I’m using the web application template.

>> Ooh sorry, I didn’t actually actually switch over to the screen.

>> That’s all right. There it is inside of a view Few imports and then the school view.

>> Tops the HTML.

>> And this is what you get. I’m using the web application template, which is the one that got a lot of stuff predefined. If you’re starting from empty, then you’ll need to install that new package in order to get that stuff. Okay, so empty as we know is pretty empty. Even images aren’t rendered by default. So you’ll need to have package in there but if you’re starting with the web application, that’s in there by default.

>> Okay, so that is inside the view imports folder

>> Yeah.

>> Which is like a, that’s a convention. View import a convention that can apply to every view view

>> Yes, yeah.

>> So, if I make change we’ll see in a second how we use that to.

>> Yeah.

>> So what we’re gonna do now. So now, in some what tech helpers are we’re going to actually look at creating our own tech helper.

>> Yep, okay.

>> Now then have you ever played with the Stack Overflow API? No.

>> Not in at C#.

>> I’ve done it through their web interface.

>> Okay.

>> SQL like.

>> So it’s a really good api. And I’m just gonna copy, so I’m using post man here. I’m just gonna do, cuz this is just a standard request for questions on Stack Overflow.

>> [INAUDIBLE] smallest font.

>> I know, but don’t worry, cuz this [CROSSTALK] I’ve fixed it. So what this does, it’s a great API. It’s open, but when you look at dates, it returns these weird strings. Now, that doesn’t look like a date to me, and I was confused when I first looked at this.

>> Yep. That is actually something called an epoch string.

>> All right, okay, so, we’re talking about epochs.

>> Epochs, epoch, yeah.

>> When we were in the production, I thought you said ewoks.

>> Ewocks?

>> Yeah.

>> No, not ewoks, no. [LAUGH]

>> That’s why I put that on.

>> That’s Star Wars.

>> I thought it was strange, I thought Stack Overflow would be returning ewoks.

>> Yeah, well, no. Maybe they do. There’s a question about, maybe there’s a tag for Ewoks, in Stack Overflow. But no, we’re talking about epochs.

>> Epochs, okay.

>> Well,

>> [SOUND]

>> Yeah.

>> Ewoks will do.

>> Yeah, that’s fine. So an epoch is a thing that’s in Unix, and it’s quite a strange concept really, but it makes sense. So the time is represented by the number of seconds from the first of January 1970.

>> Yeah, and so, that number of seconds there, is how many seconds from-

>> That number-

>> Yeah.

>> I used to work on a pick database, which had exactly the same sort of database too. I think, so it’s quite a common way to handle-

>> It is, yeah. I think it runs out in 2024, some days in the future.

>> A limit of the integer.

>> Yeah, but it’s nice, cuz it is just an integer and you can work it. What we’re going to build is a tag helper that will take epoch dates and convert them to real dates, so we can actually implement. So, we’re gonna start off by just creating a new project, which I just go to Visual Studio. I’m just gonna do this as a web application project for now. Go to web and I’m just going to call this, let’s call it ewok. I mean, might as well, and just click OK for that. And we choose a web application just to save me avoiding all of the, going for the NuGet stuff for MVC and stuff. I don’t need the authentication for this, it doesn’t really matter whether that’s there or not. And so by convention, so tag helpers are, basically, they’re classes, they’re just simple classes that implement that ITagHelper Interface. So by convention we’re gonna just create a folder called TagHelpers. It doesn’t really matter where they go, but just by convention you create a folder in the root of your project called TagHelpers.

So we’re gonna do that very quickly, as soon as Visual Studio catches up with me. I’m obviously that fast there. It’s talking to the keyboard. So I’m going to create a folder called TagHelpers. And I’m going to add the classes folder called epoch tag helper. And these can obviously be distributed as a. It’s just a classic.

>> Yeah.

>> I mean, in lots of different ways, doesn’t have to be included [INAUDIBLE].

>> Exactly, yeah. And the ones which come with MVC are a nuGet package, right?

>> Yeah, Well, I think they’re in that nuGet package we looked at earlier, I think. So EpochTagHelper, so again by convention, the file name should be typed something, type TagHelper, like if it’s something controlled then MVC. It doesn’t really matter, but this is a convention. So that’s my basic epoch tag helper. So the first thing I want to do to turn this into tag helper is just hit inherit, implement TagHelper. And then I just need to resolve my little using statement there. So this is now officially a TagHelper class. Okay, and so just to get us started, I’m gonna just copy some code from my second manager here, and paste this in here. So TagHelpers have two functions that can be overridden process and process async. And that’s basically, the bit of code that executes the tag helpers. So, what this one does, quite simply, is it just sets the output as fictional race of small, mammaloid bipeds. Which is what an ewok is. So, that’s that there. That’s the tag helper is done.

And now to be able to use this tag helper we need to go into our view imports. And we need to have, one second, we need to add the namespace in here. So it’s add TagHelper And it’s going to be *, I need to be careful here, cuz I’ve called it ewok. Let me just check what I’ve called it, ewok.Taghelpers, there we go. *ewok.Taghelpers. Well actually, I think we can just do ewok and that just means the whole project.

>> Right, okay.

>> So what I’m doing here is I’m basically, as well as using the Mvc.TagHelpers nuGet package, I’m saying I can use my own TagHelpers as well. And now, it means that all of the views are available, all of the views can now use any TagHelpers that are in that namespace, effectively. Okay, so that’s great and I’m just gonna build the project now and now. What we’re gonna do is we’re gonna go to our view and actually start to use this. So I’m just gonna go to the index view for now. I’m just gonna throw a h1 just so it’s not as big and we can see what we’re doing. And I’m just gonna type in epoch, and close it. And you’ll see that’s gone that lovely shade of green.

>> Epoch, ewok, I thought it was ewok.

>> Well, I’ve called the project Ewok, but I’ve called the tag helper epoch.

>> I see, we’re getting confused. [LAUGH]

>> Yeah, and that’s why I struggle slightly with the imports, cuz is it an ewok or an epoch?

>> So if you go back to the class implementation.

>> Yeah. If we go into this one. So, the class itself, is called epoch tag helper.

>> So, just like in MVC, you’ll ignore the tag helper there.

>> So, there’s a naming convention.

>> There’s a naming convention, yeah.

>> So, that epoch will become the tag. Yeah.

>> By default.

>> By default, yeah.

>> And there are attributes that you can add to that class to override that.

>> Yeah, so if you wanted to target an existing tag you can do that. There’s a lot, I mean, this is out of scope for this, but there’s lot’s of variations to this but for just influencing your own TagHelper like we’re doing here, that’s the convention. So you call it EpochTagHelper so it will allow you to simply go Epoch in your markup.

>> Right, okay.

>> Okay so let’s just see what this does just by default. So as you’d expect. This is gonna simply tell us, Ronnie.

>> Right, okay.

>> Okay, so all I’ve had to do in my markup, I’ve just written tag helper epoch and that has generated that string there. So, that’s kind of your hello world example basically.

>> Yep, [CROSSTALK] fictional race of small,

>> Mammaloid bipeds [INAUDIBLE]?

>> Mammaloid [CROSSTALK].

>> [INAUDIBLE] jam.

>> It’s marmalade

>> Yeah.

>> [LAUGH]

>> Okay.

>> It doesn’t seem like it’s a word that has [INAUDIBLE] I’m gonna move on.

>> [LAUGH]

>> So let’s start to put some codes in here now. Let’s actually do something sensible. So we’re gonna get rid of that. We can get rid of that as well. We don’t need that anymore. And I’m just gonna paste a little bit of code in here. That does the epoch conversion. So what this code does, is first thing it gets the child content so this line of code here will get the, what’s contained within the tag. So we’re gonna put our epoch string within that tag, and this will get into this childContentRaw. I’m then going to start with a date time variable for the 1st of January 1970. Then I’m gonna simple add the number of seconds, and that’s going to give me a display date, and I’m going to display that as a string. Really simple, okay. So what we’re gonna do now is go back into index, and I’m just gonna put in an epoch date here. So 299442480. And we’ll reveal what date that is in a second. It’s a little bit of suspense for you there. If I’ve typed it right, let me just double check I’ve typed it right.

Yes, I have typed it right. So let’s just run that and see what we’ve got. There we go. And that is the exact minute that I was born.

>> Wow. Okay, as an epoch.

>> Okay, so if anyone wants to know.

>> Anybody wants to know.

>> If anyone wants to sort of compromise your banking security.

>> And do some identity fraud. Go ahead, go for it.

>> What’s your mother’s maiden name.

>> Yeah, we’re not gonna go there. But that’s kind of cool though, right? So if I was using the Stack Overflow API, and I’m getting these epoch things returned. I don’t need to do any conversion in my control or my view model or any of that kind of stuff.

>> If you just want it to display that.

>> Yeah, imagine if I was trying to do that in my razor view or I just want to take the data directly from the data that’s come back of the API and just display at it as a date.

>> And likely as well if you want to do something like there’s a great little JavaScript like we call moment.js, which converts date into readable human dates.

>> Okay.

>> So it sort of if it was like a few seconds ago,

>> Yeah.

>> It just says a few seconds ago. Or if it was an hour ago, it says an hour ago.

>> Well you could do the


>> Now it says much later. Well I think moment.js does that in JavaScript. But the initial render of that could absolutely be done on server side and then subsequent updates so if you left the page open for an hour and update would be using JavaScript maybe.

>> But that would be the perfect example of where you’ve got quite a straightforward piece of data but you’ve got a far more complicated display.

>> Yeah, exactly. Yeah. So talking about more complicated displays. I feel that that display, though it’s nice, it’s human reads but it’s still a little bit complicated. I’d like something a little bit more friendly than this.

>> Okay. Yeah. So I’m going to take it to the next level.

>> Okay.

>> Okay? I’m going to take this tag helper to places where tag helpers rarely go. [LAUGH] And I’m going to make it so that I can pass in a formatter. A formatter, so that I can add in a date format, basically.

>> [INAUDIBLE] computer.

>> So these are my snippets. But I’m just going to code out, it’s fine.

>> So I’m gonna add the string, a public string, to my tag helper, and call this formatter. And then I’m just gonna say in my two string I’m just gonna put the formatter. Now what that’s going to enable me to do is in my mark up, I’m just gonna build this again quickly. This will allow me to add an attribute to my tag helper, where I can define in my marker how I want to format the string. So I want to display it in sort of a nice friendly, I just want the date maybe, so I’m gonna go “dd MM yyy”.

>> It’s 3M 3y.

>> Yeah, that should display a date of some sort. So I’m obviously using the standard .NET date formatting stuff. You can put any string in there that you want, as long as it’s a date string formatter. And then let’s run that again, and it should just display the date rather than the date and time. Okay.

>> Very cool.

>> So,

>> If you go back to that C# implementation there,

>> Yeah, just gonna do this.

>> So I can feel like a follow, just so the attribute formatter, that maps through to a C# object? The property, just the property.

>> So, yeah. So the property formatter that maps onto this property here in my code formatter.

>> Okay.

>> So basically what it’s saying is just a string and it’s being passed into my code basically from the marker. And all I’m doing is I’m applying that formatter to my two strings.

>> Two strings?

>> Yeah.

>> So it just has a property of right which is accepting that string?

>> Yeah.

>> The format the known format?

>> Exactly. Yeah and there’s some conventions with this, as well. So, things like if you have, let’s say I was to do something like public string, let’s call it DateFormatter. There’s a slightly odd convention which I discovered if I build this. When you’re referencing that in your index, you have to call it date. And there’s a name for that. I can’t think what it is, but with the hyphen in there. I can’t think what it is now. Maybe in post production we can come back and tell the viewers what that is.

>> So, what is this one? I can’t believe you didn’t remember what it was.

>> No, I don’t either now. So if we go to docs.asp.net, on there, there’s a tutorial called Authoring Tag Helpers which almost to the content for the show that we’ve just done.

>> Okay.

>> Now in here, we scroll down and they use an idea of a mailto for doing email. So if we look at in the C#, we got a string called MailTo. If you look at the notes, it says here. Pascal-cased class and property names for tag helpers are translated into their lower kebab case.

>> Kebab case.

>> So that’s what it’s called, that thing. [CROSSTALK] And so there’s some funnies around that, but that’s all kind of low level detail. The point is tag helpers are a cool way to kind of take server-side work and make it very easily visible for your markup. And also, to the app to [INAUDIBLE] tags rather than using these HTML holders and having this weird kind of markup that only .NET people would understand. We can just implement very standard looking form very standard looking HTML and have other people work on it, basically.

>> Okay, well that’s it for another Web Hack Wednesday. Thank you very much to Martin. Thank you very much to the Ewoks. We’ll see you again next Wednesday for another web topic.

>> Cool.


Read the video

This week Martin and Martin look into Tag Helpers a new feature in Razor views inside of ASP.net Core. They build a basic tag helper and consume it from within an ASP.Net Core project.

Comments to Tag Helpers in ASP.Net Core

  • Why there is no release date announcement for ASP.NET Core? We expected that it will be released in January this year, but now I see that there is another RC planned for later this year and no date for RTM…

    Say May 5, 2016 6:51 am Reply
  • There is a weekly show about Asp.Net Core with Scott Hanselman and Damian Edwards. They explained multiple times that they heard the community loud and clear to make it right before releasing it. I totally support that decision. RC1 is working just fine for now and has a go live license.In the last show they announced that they would give more details about the release schedule in the upcoming show. ASP.NET Community Standup – May 3rd, 2016 – Orchard CMS on .NET Core on Ubuntu

    Flynn0r May 5, 2016 11:04 am Reply
  • very good, thank you.

    Beginner May 6, 2016 7:55 am Reply
  • @Say:See the comment below from @Flynn0r. They are taking the approach of "we’ll release when it is ready". Follow Live.asp.net for the latest updates.

    MartinKearn May 9, 2016 2:28 am Reply

Leave a Comment

Your email address will not be published. Required fields are marked *

1Code.Blog - Your #1 Code Blog