Skip to content

Instantly share code, notes, and snippets.

@rbaarda
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbaarda/b2a753f09053411859bb to your computer and use it in GitHub Desktop.
Save rbaarda/b2a753f09053411859bb to your computer and use it in GitHub Desktop.
EPiServer default page controller which uses page type name as controller name in view locations.
using System.Web.Mvc;
using Example.Models.ViewModels;
using EPiServer;
using EPiServer.Core;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Web.Mvc;
namespace Example.Controllers.Pages
{
[TemplateDescriptor(Inherited = true)]
public class DefaultPageController : PageController<PageData>
{
public ViewResult Index(PageData currentPage)
{
IPageViewModel<PageData> model = PageViewModel.CreateModel(currentPage);
return DefaultPageViewResult(currentPage.GetOriginalType().Name, model);
}
private DefaultPageViewResult DefaultPageViewResult(string name, IPageViewModel<PageData> model)
{
ViewData.Model = model;
return new DefaultPageViewResult(name)
{
ViewName = "Index",
MasterName = null,
ViewData = ViewData,
TempData = TempData,
ViewEngineCollection = ViewEngineCollection
};
}
}
}
using System.Web.Mvc;
namespace Example.Controllers.Pages
{
public class DefaultPageViewResult : ViewResult
{
private readonly string name;
public DefaultPageViewResult(string name)
{
this.name = name;
}
protected override ViewEngineResult FindView(ControllerContext context)
{
context.RouteData.Values["controller"] = name;
context.RouteData.Values["action"] = "Index";
return base.FindView(context);
}
}
}
using Example.Models.Layout;
using EPiServer.Core;
namespace Example.Models.ViewModels
{
public interface IPageViewModel<out TPage>
where TPage : PageData
{
TPage CurrentPage { get; }
ILayoutModel Layout { get; set; }
}
}
using System;
using Example.Models.Layout;
using EPiServer;
using EPiServer.Core;
namespace Example.Models.ViewModels
{
public class PageViewModel<TPage> : IPageViewModel<TPage> where TPage : PageData
{
public TPage CurrentPage { get; private set; }
public ILayoutModel Layout { get; set; }
public PageViewModel(TPage currentPage)
{
CurrentPage = currentPage;
}
}
public static class PageViewModel
{
public static IPageViewModel<TPage> CreateModel<TPage>(TPage page) where TPage : PageData
{
Type type = typeof(PageViewModel<>).MakeGenericType(page.GetOriginalType());
return Activator.CreateInstance(type, page) as IPageViewModel<TPage>;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment