Creating HTML Helpers

5 Feb 17

What is an HTML Helper?

 

It's a piece of Razor code that you can call from multiple locations on your page. 

 

Here's an example:

 

Create this at the top of your page.

 

@Helper ShowWarning(ByVal warningText As String)
  <span class="warning">
    @warningText
  </span>
End Helper



To reference this from anywhere within the page.


@ShowWarning("Oh No! There has been an error")

If you feel that this code will be useful enough to use across all your views you can create a global helper.  To do this:

 

  1. Right click on the app_code folder
  2. Select "Add > New Item"
  3. choose "helper" under the Razor templates
  4. Give the file a name.  Let's call ours "dwHelper".
  5. and put in the helper code above.

 

You have now made your helper globally accessible.

 

You will need to make a slight change to your code that calls the helpers now:

 

@dwHelper.ShowWarning("Oh No! There has been an error")




Comments

Darren Welch

By

Darren Welch


  5 Feb 17


Contact me online

 Facebook

 Twitter

 Linked In

 Git Hub