How To Pass Parameters Between A Content Area To a Block

In today's guide, I'm going to explain how you can 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 then it makes more sense to do all the work on the page.  In these instances, I'd recommend maybe considering looking at property<t> instead.  If that statement is completely meaningless to you, then I recommend 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 ContentAreas out of the box there are a number of different properties you can set to change the type of tags that the enclosing markup uses, the CSS class it outputs. For more information on this, see Extra divs in content area how to remove them?

When we pass parameters into content areas like this we're adding them to the view bag. If you want to pass in your own custom properties you can hook into this pipeline.

                  @Html.PropertyFor(x => x.CurrentPage.ContentArea
                            CustomParamter = "myvalue"

In your block controller, you can now access that parameter using the following snippet:

        public override ActionResult Index(MyBlock currentBlock)
            var myProperty = ControllerContext.ParentActionViewContext.ViewData["CustomParamter"]?.ToString() ?? string.Empty;

            return PartialView("Index");

Pass arguments down to blocks Takeaway

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 properties. I would stress that if you are thinking of doing this I'd seriously consider your architecture as it's highly likely there's a better way of doing things. Also, if you care about testing, it is my advice to wrap the ControllerContext.ParentActionViewContext.ViewData bit of code in a separate class and inject that in. If you don't do this you need to start mocking up service locators and HTTP contexts, which is tedious and painful.

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top