Motivation
I want to create a tree-like hierarchy of objects in Javascript that matches the ASP.NET MVC 3 Razor views on the page. The plan is to have a one-to-one correspondence between the Razor representation and the Javascript file, where its logic is defined (in the form of a constructor function that will take some initialization parameters). A simple example might look like this:
_Layout.cshtml <-> Global.jsSplitterPane.cshtml <-> SplitterPane.jsGrid.cshtml <-> Grid.jsTree.cshtml <-> Tree.js
I would use constructors to build a hierarchy, for example.
var page = new Global(global_options); var splitter = new SplitterPane(splitter_options); var grid = new Grid(grid_options); var tree = new Tree(tree_options); page.addChild(splitter); splitter.addChild(grid); splitter.addChild(tree);
All this code should, of course, be automatically generated in the context of the root view (layout) from metadata collected from partial views. The metadata provided by the view contains the parameters needed to initialize the Javascript object and the loaded Javascript files.
Problem
Unlike WebForms, MVC views do not have any natural hierarchy that I would know about, and transferring information between a view and its partial (sub) views seems rather complicated. When using helpers, such as Html.Action , in the view, all processing of "subview" occurs independently, so they donβt even share the Page object. I need some kind of central place where views can lay off their metadata as they are rendered so that they can be used in the layout to combine and output the full script.
Decision?
One way I could think of is to use HttpContext.Current.Items to temporarily store a collection of view metadata objects. All views will contain metadata, and the layout will use it. The order of execution seems to meet my expectation, however, I still cannot restore the hierarchy of tree views. To be able to do this, I will need to use a stack where the view will register at the beginning of its rendering and unregister at the end so that the parent can be found on top.
- Is there a way to have some pre / post-rendering hooks where I could put this logic?
- Is that even a good idea in the first place?
- Is there a completely different solution that I don't see?
source share