Is this a bug in WebMatrix PageData?

强颜欢笑 提交于 2019-12-01 08:48:15

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:

@{
    Page["Shared"] = new Dictionary<string, string>();
    Page.Shared["Title"] = "Test";
    @Page["shared"]["Title"]

    @RenderPage("~/Partial.cshtml")

    @Page.Shared["Title"]
}

// Partial.cshtml
@{
    Page.Shared["Title"] = "Updated title";
}

You layout page is overwriting the value passed to it form the partial page. To pass data from the partial page to the layout page use a different indexer.

Partial page

@{
  PageData["test"] = "value form partial";
}

Layout page

@{
  PageData["anothertest"] = "value from layout";
}
<p>test value = @PageData["test"]</p>
<p>anothertest value = @PageData["anothertest"]</p>

If you want to have a default value in the layout page that is displayed if your partial page doesn't set the value then you can do the following

Layout page

@{
  var test = PageData["test"] ?? "Layout default value";
}
<p>test value = @test</p>

Partial page

@{
  PageData["test"] = "partial page value";
}

If your partial page does not set PageData["test"] then "Layout default value" will be used

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!