As part of our continued series on Sitecore MVC, we addresses the change to the presentation level of the Experience Editor by providing a method for creating custom HTML helpers. 

When switching from  Web Forms to MVC things get very different in the presentation layer- no more code-behind, no more user controls. Fortunately, Sitecore provides us with some useful html helpers, namely Field() and Placeholder(). These helpers allow us to render content that can be edited in the Experience Editor and setup placeholders for nested layouts respectively. Here is a sample of how both can be used:

Field() – Synonymous with sc:Text in WebForms

 Sitecore MVC helper 

Placeholder – Synonymous with sc:Placeholder in WebForms

Sitecore MVC helper    

We can of course create custom html helpers and in this blog post I will create a label helper, which enables developers to add labels to pages to ensure that there is no hard coded text anywhere and that all text can be translated using the Sitecore client interface.

First things first, I will create a class library project and add it to my existing solution. I recommend a naming convention for your library to be YourProjectName.Mvc. Next, we need to create a Html Helper extension class in the root of our new class library which will create a new instance of a Helper class (that we will create in the following steps). This class also ensures that we access the same helper object, which is attached to the current thread to avoid memory issues for helper methods that may be called numerous times in a single view.

Sitecore MVC helper

To access the MyHelper methods from our views the next step is to open up the web.config file in the Views folder of our solution and add the namespace to the existing list.

Sitecore MVC helper
            

We will now see our new namespace appear in intellisense in our view

Sitecore MVC helper      


Helper method implementation

In our HtmlHelperExtensions class we create a new instance of MyHelper where our code will go. I have created an overloaded method, Translate, which provides the option of specifying the default text for a label being created for the first time. We must provide a key, which is the unique identifier for the label. Initially, I've set the label text returned to the View as the key, but I have included some markup with a CSS class so that labels can be styled (In future iterations an additional override could be provided so that the class can be set from the view).

Sitecore MVC helper

The additional options are now available in our view:

Sitecore MVC helper       

And finally returning to my helper class, I add an additional method which contains the business logic to get or create a label item in the content tree and return its value in the context language (falling back to en if no translation is specified).

Sitecore MVC helper


comments powered by Disqus