Views: 410
Number of votes: 13
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

    (By Henrik Fransas , 21 March 2017 10:26, Permanent link)

    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<IContentRepository>().Get<RegistrationPage>(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 post a comment