Keystone: Adding an MVC view to an existing component

keystone-logoSome Keystone components, like the Accordion and Tabs components, have multiple views. This allows developers to have a different markup for different states. For example, you can present a Page Editor view or a specific view if certain pieces of data are missing. Use the following steps to extend Keystone components to add your own MVC view.

The View

The first step, of course, is to create your new View for the component. The easiest way is to locate an existing View for that component and duplicate it. By doing this, you will have an example of how to use the ViewModel for that component. Most components have their own folder where you can group your views together.

At this point you can alter the markup of your new View to meet your needs.

The Rendering

Keystone components are configured in Sitecore as Controller Renderings. This means you do not need to add a Rendering definition in Sitecore for your new View.

You should take a look at the controller rendering for your component, though, to find out which controller action it is using.

The Controller

Once you’ve located the controller and the controller action, you will need to adjust the business logic to load your new view. The below example is how you could load a different view for Page Editor mode.

var model = DataSourceItem != null ? new SimpleText(this.DataSourceItem) : null;
var viewResult = model != null ? this.View(model) : this.View();

if (Sitecore.Context.PageMode.IsPageEditor)
{
	viewResult = this.View("SimpleTextPageEditor", model);
}

return viewResult;

That’s it!

From here, you can continue to evolve the controller logic to continue loading different views as needed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s