【问题标题】:NullReferenceException in usercontrol from class library, but not from web project来自类库的用户控件中的 NullReferenceException,但不是来自 Web 项目
【发布时间】:2022-02-05 23:06:19
【问题描述】:

我有以下项目结构,其中 Web 应用程序可能包含来自同一 Web 项目或单独类库的用户控件。问题出在 Default.aspx.cs 中,当我执行 usercontrol2.SetValues(); 时,我收到了 NullReferenceException,因为由于某种原因,textbox2 为空。我试过使用EnsureChildControls();,但也无济于事。我应该以其他方式注册或调用这些用户控件吗?为什么它不能开箱即用?

网络项目中的用户控制

WebUserControl1.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>

<asp:TextBox runat="server" ID="textbox1"></asp:TextBox>

WebUserControl1.ascx.cs

namespace WebApplication1
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        public void SetValues()
        {
            textbox1.Text = "Hello";
        }
    }
}

类库中的用户控件

WebUserControl2.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl2.ascx.cs" Inherits="ClassLibrary1.WebUserControl2" %>

<asp:TextBox runat="server" ID="textbox2"></asp:TextBox>

WebUserControl2.ascx.cs

namespace ClassLibrary1
{
    public partial class WebUserControl2 : System.Web.UI.UserControl
    {
        public void SetValues()
        {
            textbox2.Text = "world";
        }
    }
}

主页

默认.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register tagPrefix="web" tagName="WebUserControl1" src="WebUserControl1.ascx" %>
<%@ Register TagPrefix="web" Namespace="ClassLibrary1" Assembly="ClassLibrary1" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <web:WebUserControl1 runat="server" ID="usercontrol1"></web:WebUserControl1>
    <web:WebUserControl2 runat="server" ID="usercontrol2"></web:WebUserControl2>
</asp:Content>

默认.aspx.cs

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            usercontrol1.SetValues(); // OK
            usercontrol2.SetValues(); // NullReferenceException
        }
    }
}

【问题讨论】:

    标签: asp.net webforms


    【解决方案1】:

    无法使用来自不同程序集的 ascx 用户控件。

    我认为你应该这样看待这个问题。你的类库被编译成一个 dll 文件。这是唯一可用于您的 Web 应用程序的东西。 “ascx”没有被编译到 dll 中,并且不可用。

    如果您真的想将一些控件与您的网络项目分开,我认为有几个选择:

    1. 将您的用户控件转换为自定义控件。自定义控件创建起来有点困难,但这当然不是不可能的。这样你就真的得到了一个可重用的控件。 另见这个问题;它解决了您的问题,并且还有一个算法的链接,该算法将 ascx 用户控件“转换”为自定义控件。 (我没有测试过) Asp.NET user control referenced from another project/dll has NULL properties

    2. 通过发布到输出中的路径,确保您的 ascx 文件可用于网络项目。然后使用 LoadControl 在服务器端加载它们。这可能有效,但我也认为您的类库中的一些可重用性丢失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 2023-04-11
      • 2011-01-17
      • 1970-01-01
      • 2013-04-21
      • 2012-07-01
      • 2021-01-24
      相关资源
      最近更新 更多