I think I may have found a bug in WebMatrix’s PageData, but I am not sure.
It concerns how to pass data from a partial page back to a calling page.
In the WebMatrix documentation (tutorials, e.g. “3 – Creating a Consistent Look“, and example code), PageData is recommended as a mechanism to pass data between pages (e.g. from a content page to a layout page, or to a partial page).
However I have found that this does not always work the other way, to pass data from a partial page back to the calling page. Modifying or adding entries in PageData in a partial page, does not seem to get back to the calling page.
Cutting this right down a the simplest possible example, in a test page we may have this:
@{
PageData["test"] = "Initial entry";
}
<p>Before calling the partial page, the test value is @PageData["test"]</p>
@RenderPage("_TestPartial.cshtml")
<p>After returning to the calling page, the test value is @PageData["test"]</p>
and in the _TestPartial.cshtml page we might have this:
@{
PageData["test"] = "Modified entry";
}
<p>In the partial page, the test value has been modified to @PageData["test"]</p>
The resulting output is this:
Before calling the partial page, the test value is Initial entry
In the partial page, the test value has been modified to Modified entry
After returning to the calling page, the test value is Initial entry
So the modification that the partial page made to PageData is lost when you return to the calling page. The same occurs if we add new entries to PageData in the partial page. They are just lost on return to the calling page.
I don’t know if this behavior a bug, or if is it intentional, but it leaves you without a clean way to pass data from a partial page back to its calling page. Is there another (relatively clean) way to do that? Alternatively, if it is a bug, is there a work around?
Cross-posting my response from: http://forums.asp.net/t/1667665.aspx/1?Is+this+a+bug+in+WebMatrix+PageData+
This is going to sound trite, but the behavior is by design and not a bug. When a partial page is initalized, a copy of the PageData dictionary is passed to it, which is why the values remain unaffected in the original page.
To share values across pages and partials for the lifecycle of a request, you could use Context.Items. Alternatively, you could drop in a dictionary or an ExpandoObject inside PageData and use that to share values: