在母版页中找不到`MainContentPlaceHolder`或在ASP.NET中返回NULL

时间:2019-01-23 14:55:49

标签: javascript c# html asp.net bootstrap-4

我有一个名为Alerts的类,它是从BootstrapPage继承的。经过一些操作后,我将此类用作用户的MessageBox。这是代码

public class BootstrapPage : Page
{
    public enum WarningType
    {
        Success,
        Info,
        Warning,
        Danger
    }

    public void ShowNotification(string message, WarningType type)
    {
        var mainContentHolder = Master.FindControl("MainContentPlaceHolder") as ContentPlaceHolder;
        Panel notificationPanel = new Panel();
        {
            LiteralControl closeButton = new LiteralControl();
            closeButton.Text = "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>";

            Label notificationMessage = new Label() { Text = message };

            notificationPanel.Controls.Add(closeButton);
            notificationPanel.Controls.Add(notificationMessage);
        }
        notificationPanel.CssClass = string.Format("alert alert-{0} alert-dismissable", type.ToString().ToLower());
        notificationPanel.Attributes.Add("role", "alert");

        mainContentHolder.Controls.AddAt(0, notificationPanel);
    }
}

我有一个名为MasterPage的{​​{1}},在这里(简化代码以更好地理解)

Site.Master

这是<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="DeceasedSystem.Site" %>

HTML

这是<!DOCTYPE html> <html> <head runat="server"> <link href="css/bootstrap.min.css" rel="stylesheet" /> <link href="css/Style.css" rel="stylesheet" /> <link href="css/select2.css" rel="stylesheet" /> </head> <body> <form id="form1" runat="server"> <div class="col-md-9"> <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html>

contentPage

现在,当我登录时,它会在此行上抛出<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="UserProfile.aspx.cs" Inherits="DeceasedSystem.WebForm1" %> <asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"> </asp:Content>

NullReferenceException

这是图片。 enter image description here

当我提供 var mainContentHolder = Master.FindControl("MainContentPlaceHolder") as ContentPlaceHolder; 并且它存在于我的NullReferenceException中时,我不知道为什么会抛出MainContentPlacholder。请帮帮我,因为我不了解MasterPage,还有它抛出此Exception的原因是什么。 注意:我是Exception的{​​{1}}个网页。这与Inheriting有什么关系吗?帮帮我。请

0 个答案:

没有答案