Just wondering what the actual difference between the ViewData that is bound to the MVC view and the ViewData that is bound to the @Html helper object?
I have written a page and they don’t seem to refer to the same thing. Is ViewData used anywhere else in the application as another dictionary hidden under the same name?
SHORT ANSWER:
The
HtmlHelper‘sViewDatais based on the view’s data. So it has same values upon entering view code (for example, Razor or ASPX page). But you can change theseViewDatas separately.It is used same way in
AjaxHelper.RepeaterItemhas it’s own ViewData, which is based on the item.I have not found any use of different
ViewDataanywhere.UPDATE:
ViewDataand@Html.ViewDataare different only when you use a strongly typed view. If you use a not strongly typed view, both they are equal as reference. So I think this was done to wrap theViewDatainto strongly typedViewDataDictionary<>.SOME INVESTIGATIONS:
I have taken a look at the decompiled sources and here is what I found.
Let’s see, what is @Html.ViewData:
As we see, the
ViewDatais instantiated from someviewDataContainerinHtmlHelperconstructor.Let’s try to see, how is this connected with the page:
So the current page is the
viewDataContainer.So, we see, that a new instance of a
ViewDatadictionary is instantiated forHtmlHelperbased on the dictionary, which is stored inView. The only option, which could make the two be kinda same, if they used sameDisctionaryinternally. Let’s check that.Here is
ViewDataconstructor:As we can see, entries a just copied, but a different underlying
_innerDictionaryis used.