Accessing CurrentPage from blocks in MVC

Vote:
 

Hello

I know blocks have their own model and are isolated so that they can be used regardless of page.

But if I want to access CurrentPage from a block, what is the best way to do this, in MVC?

In this case a set of blocks should have different image size on certain pages, but apart from that they are identical and I don't want to duplicate the code.

I added this to block base class;

public PageData CurrentPage {
	get
	{
		var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<EPiServer.Web.Routing.PageRouteHelper>();
		return pageRouteHelper.Page;
	}
}

Which works fine for me.

Another way could be to add a value to viewdata that the controller/view of the page can pass on to the block shared view.

Any thoughts? Other solutions?

Thanks
Fredrik

#80104
Jan 15, 2014 8:46
Vote:
 

In cases like these, I've always preferred to work with the existing template rendering solution already included in EPiServer 7 http://world.episerver.com/Blogs/Johan-Bjornfot/Dates1/2012/9/EPiServer-7--Rendering-of-content/

What this means is that you can just create another renderer (view in MVC) for your block. This means you don't have to couple your block controller logic to specific page types or even make it have any contextual currentPage knowledge,

Your alternative view would have the different image size. You would then add a rendering tag to the contentareas used by the page types where you. require the alternative view, and EPiServer will select the view that matches the tag withoutvany further logic or any code duplication

You could argue that having 2 views with very similar markup is also duplication, but in my mind it is the least complex solution, that keeps the separation between contnet logic and presentation.

#80109
Jan 15, 2014 9:40
Vote:
 

Thanks for the advice, and for the explanation, that's good to be aware of.

The thing is, it's not only one block/view, it's a bunch of different blocks, so there's some code to duplicate, and as other developers in the future add new blocks they will need to be aware of this.

But I'm thinking maybe if I cound extract the image from the block partial view, so that all the blocks/views uses the same partial view for the image and the image is the only part affected by the renderingtag. Does that sound sane?

#80114
Jan 15, 2014 10:24
This thread is locked and should be used for reference only. Please use the Episerver CMS 7 and earlier versions forum to open new discussions.