【问题标题】:NullReferenceException when defining a custom object in ASPX在 ASPX 中定义自定义对象时出现 NullReferenceException
【发布时间】:2014-08-21 22:30:20
【问题描述】:

我正在尝试创建一个自定义上下文菜单作为用户控件。此用户控件的代码如下所示:

public partial class UCContextMenu : UserControl
{
    private List<ContextMenuItem> m_menuItems = new List<ContextMenuItem>();

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public List<ContextMenuItem> Items
    {
        get { return m_menuItems; }
        set { m_menuItems = value; }
    }

    public event EventHandler Command;
}

然后,我定义了ContextMenuItem 类型在同一个命名空间中作为用户控件(实际上在同一个文件中),它本质上是一个菜单项:

public class ContextMenuItem
{
    public string Name { get; set; }

    public string Text { get; set; }
}

用户控件的ascx 页面包含一个repeater 控件,其定义如下:

<div id="contentHolder">
    <ul id="ulContextMenu" style="display: none; z-index: 1000; border-width: 0.8px;
        font-size: 13px;" class="ui-corner-all">
        <asp:Repeater runat="server" DataSource="<%# Items %>">
            <ItemTemplate>
                <li><a href='#<%# DataBinder.Eval(Container.DataItem, "Name") %>'>
                    <%# DataBinder.Eval(Container.DataItem, "Text") %></a>
                </li>
            </ItemTemplate>
        </asp:Repeater>
    </ul>
</div>

最后在注册后在页面中使用它,我有:

<uc:ContextMenu runat="server" OnCommand="SomeMethod">
    <Items>
       <uc:ContextMenuItem Name="SomeName" Text="SomeText" />
    </Items>
</uc:ContextMenu>

现在,当我运行它时,我在线上收到 NullReference 解析错误

<uc:ContextMenuItem Name="SomeName" Text="SomeText" />

当不运行时,Visual Studio 也会说 Element 'ContextMenuItem' is not a known element. 它在运行时也不会捕获异常,所以也许这样我可以查看堆栈跟踪以了解发生了什么。我只是想知道是否有人遇到过类似的问题。任何帮助表示赞赏。

【问题讨论】:

  • UCContextMenu 继承 UserControl。 ContextMenuItem 没有。这有关系吗?
  • 它不继承自UserControl,因为它不是用户控件。这是一个容器类。
  • 对我来说它看起来像一个普通的老班。它似乎应该继承某些东西或以某种方式将其标识为容器类。
  • 它应该继承什么?我见过的所有类似代码都只是没有继承的普通类。
  • 检查forums.asp.net/p/1552731/3811467.aspx,因为它可能适用...

标签: c# asp.net templatebinding


【解决方案1】:

创建ContextMenuItem 作为普通用户控件。您在与您强调的相同名称空间中定义它的事实对您没有任何帮助。 因此,只需将 ContextMenuItem.ascx 添加到您的项目中,然后 register and add 页面上的控件或其他控件即可。

【讨论】:

  • 我不应该将ContextMenuItem 设为用户控件。
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2013-02-27
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多