How to change the sequences of child actions in MVC
I want to generate HTML head section in a child action; while the page has many other child actions. The html head section is depended on the other actions to determine which js/css files should be included. Different child act开发者_如何学Goions could share the same js/css file; and different pages have different combination of the css/js, so there is a reason to do that. Here is my sample code:
Layout.cshtml:
<html>
<head>
@RenderZone("header")
</head>
<body>
@RenderZone("zone1")
@RenderZone("zone2")
@RenderZone("zone3")
</html>
Each zone has 1 or many child actions.
The RenderZone is atually an action too. The data mode:
Model = GetAllChildActions(zoneName)
The RenderZone view:
foreach(var m in Model)
@html.action(controller = m.controller, action = m.action)
Because the Header zone is the top so it is always executed first then it cannot get data from other child actions. I have tried filters (onActionExecuted; onActionResultExcuted and so on) but none of them works. I really need to execute the header action after all child actions are rendered. I do not want to generate the css in the bottom of a page. I could but I do not want to use javascript to inject the js/css files; or write an http module to "manually" change the output html. It is very easy to handle it in webform. I believe there is a way to do that in MVC too. Any help will be greatly appreciated!
You can pre-render of all the child actions:
@{
var prerender = new Dictionary<string, MvcHtmlString>();
prerender["header"] = RenderZone("header");
prerender["zone1"] = RenderZone("zone1");
}
And then in the body:
@prerender["header"]
This way you can have all the children perform their execution prior to rendering the first zone in your view and store the script/css registrations in the current HttpContext.
精彩评论