Srinivasan M
Mar 20, 2017
  23549
(14 votes)

Get CMS content using content reference ID

To get CMS content from Episerver using content reference ID anywhere in the MVC application using below code.

var contentReference = new ContentReference(163);
var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>().Get<RegistrationPage>(contentReference);

var model = new CMSPageModel<RegistrationPage, RegisterViewModel>(pageRouteHelper);
model.ViewModel = new RegisterViewModel();

Now you can use this model.ViewModel object to render CMS content in MVC view

Mar 20, 2017

Comments

Henrik Fransas
Henrik Fransas Mar 21, 2017 10:26 AM

There are some of stuff you need to fix for this code to be usefull.

First:

If you are just getting content from the database you should use IContentLoader instead of IContentRepository

Second:

You should never!!! write this as a one line of code:

var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance().Get(contentReference);

You should if you can get the instance of IContentLoader (thats the one you should use) with dependency injection and then you should use TryGet insted of get since Get will throw an exception if there are no page.

Please login to comment.
Latest blogs
Multiple Anonymous Carts created from external Head front fetching custom Api

Scenario and Problem Working in a custom headless architecture where a NextJs application hosted in Vercel consumes a custom API built in a...

David Ortiz | Oct 11, 2024

Content Search with Optimizely Graph

Optimizely Graph lets you fetch content and sync data from other Optimizely products. For content search, this lets you create custom search tools...

Dileep D | Oct 9, 2024 | Syndicated blog

Omnichannel Analytics Simplified – Optimizely Acquires Netspring

Recently, the news broke that Optimizely acquired Netspring, a warehouse-native analytics platform. I’ll admit, I hadn’t heard of Netspring before,...

Alex Harris - Perficient | Oct 9, 2024 | Syndicated blog

Problem with language file localization after upgrading to Optimizely CMS 12

Avoid common problems with xml file localization when upgrading from Optimizely CMS 11 to CMS 12.

Tomas Hensrud Gulla | Oct 9, 2024 | Syndicated blog

Optimizely Autocomplete (Statistics)

A user starts typing in the search input, and it returns suggestions for phrases they might be searching for. How to achieve this?

Damian Smutek | Oct 9, 2024 | Syndicated blog

Optimizely Forms: You cannot submit this form because an administrator has turned off data storage.

Do not let this error message scare you, the solution is quite simple!

Tomas Hensrud Gulla | Oct 4, 2024 | Syndicated blog