Site icon Scott Sauber

Custom Tag Helper: Toggling Visibility On Existing HTML elements

A lot of times we need a way to toggle the visibility of an element based on some server-side values.  The most common example is if someone is logged in, show them more options than someone who is not logged in.

Option without Tag Helpers

This solution always felt a little dirty to me

What I’d like to do is to add an attribute off of div to toggle visibility.  So instead I’d like something that looks like this:

So let’s create a custom Tag Helper to do this

 

Or view the GitHub Commit that makes this happen

I also have a repo, where the first two commits are just the initial commit with a File => New Project.  This 3rd commit outlines all the changes needed to make to get this to work if you’d rather learn via a Commit.

 

Breaking Down The Code

The code for the Visibility Tag Helper is pretty straight forward, but here’s a breakdown of it:

 

Update 1/3/2017: As mentioned above – thanks to Damian Edwards for informing me of the output.SuppressOutput() method.  That made things simpler.

Exit mobile version