This is an important part of your role as the architect of your application to determine what will be created by helpers and what will not, because it depends on what is repeated where and how often in your code. I am not going to tell you what to create helpers, because it depends on the architecture of your application. However, to help you make a decision, consider two general types of helpers that you can build: global and local.
Global helpers are for code snippets that are often repeated on your site, possibly with minor changes that can be handled by passing different parameters. Local helpers do the same job, but are local to this page. A page in which there is a repeating segment of code that is not found anywhere should implement a local helper. Now...
Global Helpers: Create a new static class to contain your helpers. Then create static methods inside the container class that look like this:
public static MvcHtmlString MyHelper(this HtmlHelper helper, (the rest of your arguments here)) {
What this means is to create an extension method for the Html helper class that will allow you to access your helpers using the standard Html. syntax Html. . Note that you will need to include the namespace of this class in any files in which you want to use your own helpers.
Local helpers. Another way to do helpers works when you want them to be local to a single view. Perhaps you have a block of code that repeats over and over. You can use the following syntax:
@helper MyHelper() {
Then you can display this on your page using:
@MyHelper()
The reason we always create MvcHtmlString objects is MvcHtmlString , as a security function built into MVC, the output lines are encoded to be displayed as they appear in the text on the page. This means that a < will be encoded so that you really see a "<" on the page. It will not run an HTML tag by default.
To get around this, we use the MvcHtmlString class, which bypasses this security feature and allows HTML to be output directly to the page.
source share