我的主母版页面中有以下占位符。我不想在几个内容页面中复制我的新闻内容,因此我选择不在其中提供此内容,并且母版页应提供其默认值。
<asp:ContentPlaceHolder ID="SideBarContent" runat="server">
<asp:GridView ID="newsGrid" runat="server" AutoGenerateColumns="false" Width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:ContentPlaceHolder>
当我尝试以下代码时,我收到错误,因为newsGrid为null。我假设我在页面生命周期中的错误位置执行此操作,但我不知道正确的位置在哪里。
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
if (!IsPostBack)
{
newsGrid.DataSource = _newsService.ListActive();
newsGrid.DataBind();
}
}
答案 0 :(得分:2)
ContentPlaceHolder中的内容将被内容页面提供的内容替换。
因此,当您的内容页面具有面向SideBarContent占位符的Content控件时,您的newsGrid将被替换。
考虑到这一点,您是在所有页面上看到此问题,还是只是替换内容的页面?对于替换内容页面中的内容的任何页面,我希望这是null。
更新
我刚刚尝试过这个。
如果页面未定义asp:Content
控件,该控件以asp:ContentPlaceHolder
为目标,则asp:ContentPlaceHolder
内的控件将在后面的代码中为您提供。
在一个页面中,它定义asp:Content
定位此asp:ContentPlaceHolder
,然后删除asp:ConentPlaceHolder
内的控件,因此在后面的代码中访问时为null。
因此,当内容页面提供内容时,将替换母版页上占位符中的内容,因此必须对母版页进行编码以适应这种情况。
所以,如果你在Site.master中有这个:
<asp:ContentPlaceHolder ID="OtherContent" runat="server">
<asp:Button ID="foo" runat="server" />
</asp:ContentPlaceHolder>
...然后在Page1.aspx中你有这个......
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="OtherContent">
</asp:Content>
...然后该页面的按钮“foo”将为null。如果您省略此内容控件是Page2.aspx,则会在您的母版页代码中实例化按钮foo。
protected void Page_Load(object sender, EventArgs e)
{
// this will be null for pages that
// remove the default content of "OtherContent"
var foo = this.foo;
}
所以,我怀疑你只需要防止这个网格为空,如果它是你可以假设内容页面提供了它自己的新闻列表。