ViewData property is of type
IDictionary<string, object> and is declared inside the
ControllerBase and is therefore a per request object.
And child actions are not separate HTTP requests.
So, ideally, a parent and child action should, under the design I am assuming above, share the same
However, that seems not to be the case.
So, how is this implemented? How are child actions able to have their own
ViewData and where is that code that creates a separate
ViewDataDictionary instance for child actions?
Best How To :
A child action has its own
ViewData because it has its own lifecycle.
When a request is made to the main method, its controller is initialized and the action initializes its
ViewData and begins to render its view. When
@Html.Action() is encountered, a new instance of the controller is initialized and the child action initializes its
ViewData and renders its view which is inserted at the placeholder specified by
@Html.Action() (the child actions Controller and its
ViewData is then disposed) and the main view continues to render the markup.
You can test this by creating a parameterless constructor for the controller and see that it gets initialized for each child action.
All this happens within a single HTTP request.