asp:用户控件中的Literal控件为null

The*_*iot 5 c# asp.net user-controls

我有一个包含asp:Literal的用户控件.

<div>
     <asp:Literal id="MenuContainer" runat="server" />
</div>
Run Code Online (Sandbox Code Playgroud)

代码隐藏页面中有一个初始化控件的方法:

internal void Setup(MyBusinessObject obj)
{
    MenuObject menu = MenuHelper.GetMenu(obj.State);

    if(obj == null)
        MenuContainer.Visible = false;

    //other code
}
Run Code Online (Sandbox Code Playgroud)

在使用控件的页面中,我在LoadComplete事件处理程序中调用控件的Setup方法(我在Load事件中首先调用它).无论MyBusinessObject为null还是非null,当我在用户控件上访问Literal时,我都会收到错误:

Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

是什么原因以及对此有何补救措施?

The*_*iot 11

这很简单.我在web.config的控件部分添加了一些内容,正如Rick Sthral在他的一篇帖子中所建议的那样(:(关于帖子,你将不得不在他的页面上搜索).

很好地允许我添加控件而不放置@ Register标签,但缺点是我的控件上的子控件显示为null!所以我只是将@ Register指令放在我的页面中就可以了.


Cᴏʀ*_*ᴏʀʏ 5

这取决于您在web.config中包含控件的确切方式.如果您尝试在命名空间中包含所有控件(尽管设计器将正确显示控件列表),它将无法工作:

<add tagPrefix="prefix" namespace="example.ui.controls" assembly="example.ui" />
Run Code Online (Sandbox Code Playgroud)

但是,如果您单独添加控件并指向它们的物理位置,它将按预期工作,而不必包含无限@Register指令.

<add tagPrefix="prefix" tagName="Message" src="~/Controls/Message.ascx" />
Run Code Online (Sandbox Code Playgroud)