Search code examples
c#asp.net-mvcepiserverepiserver-7

Access Current Page from a Block's Controller


I'm using EPiServer 7.7 MVC and have a scenario where I have a local / global Block MyBlock. MyBlock has a controller MyBlockController. I need to get the ID of the page that invoked MyBlockController:

 public class MyBlockController : BlockController<MyBlock>{

      public override ActionResult Index(MyBlock currentContent){
          Guid hostingPageId = ????
      }
  }

I've looked through the BlockData and ContentData classes but they don't seem to have any references to hosts.

Can I get the current page's id from the controller context perhaps?


Solution

  • EPiServer has the PageRouteHelper for exactly this purpose.
    It has a property Page that returns the current Page for the current request context.

    So your code would become:

    public class MyBlockController : BlockController<MyBlock>
    {
        private readonly PageRouteHelper _pageRouteHelper;
    
        public override ActionResult Index(MyBlock currentContent)
        {
            Guid hostingPageId = _pageRouteHelper.Page.PageGuid;
        }
    }