Views: 19554
Number of votes: 14
Average rating:

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

Henrik Fransas
( By Henrik Fransas, 3/21/2017 10:26:19 AM)

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


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


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.