In today's tutorial, you will learn how to pass parameters from a content area into a block. Before we get into the code, I should point out that I've probably only needed to do this once or twice. In most instances, if your page and your block are that related that you need to pass props between your design is probably;y flawed. It will likely make more sense to do all the work on the page and not split it into a block. In these instances, I'd recommend maybe considering looking at the
Property<T> instead. If you have never come across
Property<T>,I suggest you read this article before going any further, How To Render A List Of Object In Episerver.
How Do I Pass Parameters In My Views
When we work with a
ContentArea property out-of-the-box there are a number of default properties you can set to change the type of tags that the enclosing markup renders. For more information on this, see Extra divs in content area how to remove them?.
When we pass parameters from a view to a content area they get passed in the view bag. If you want to pass in your own custom properties into a content area you can do the same. You can hook into this pipeline using the code below:
In your block controller, you can now access that parameter using the following snippet:
As you can see, passing parameters between pages and blocks via content areas is pretty simple. Under the hood, we can hook into the normal MVC view bag to send things and access them within a controller. I would stress that if you are thinking of doing this I'd seriously consider your architecture. If you need to do this a lot then it's highly likely there's a better way of doing things. If you care about testing, it is my advice to wrap the
ControllerContext.ParentActionViewContext.ViewData in a separate class and inject that using dependency injection. If you don't do this, you will need to start mocking service locators and HTTP contexts, which is tedious and painful.
That's all there is to pass parameters into a block from your view. Happy Coding 🤘