我将一些自制的 Web 用户控件放在一个单独的项目“WebControls”中,现在想从另一个项目中重用它们
我的控件包括:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="WebControls.TestControl" %>
<asp:Label ID="lblTest" runat="server" ></asp:Label>
<asp:TextBox ID="textBox" runat="server" Width="" />
<asp:HiddenField ID="hiddenFieldId" runat="server" />
代码隐藏:
namespace WebControls
{
public partial class TestControl : System.Web.UI.UserControl
{
public Unit Width
{
get { return textBox.Width; }
set { textBox.Width = value; }
}
public string SelectedId
{
get { return hiddenFieldId.Value; }
set { hiddenFieldId.Value = value; }
}
public string SelectedText
{
get { return textBox.Text; }
set { textBox.Text = value;}
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
我像这样将它绑定(bind)到另一个项目的网页中:
<%@ Page Title="ToDo Serien" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="RecurringToDos.aspx.cs" Inherits="TestAccess.RecurringToDos" %>
<%@ Register Assembly="WebControls" Namespace="WebControls" TagPrefix="aci" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Serienelement</h2>
<aci:TestControl ID="aceRule" runat="server" Width="300" />
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" />
</hgroup>
</div>
....
当我现在启动页面时,它会在以下行中抛出 Reference Null Exception:
set { textBox.Width = value; }
因为 textBox = NULL
似乎我的控件没有正确启动。 我究竟做错了什么? 我该如何解决?
最佳答案
如果你想在多个项目中重用一个 ascx
用户控件,你应该将 ascx
文件复制到消费者项目并以这种方式注册标签:
<%@ Register TagPrefix="uc" TagName="UserControl1" Src="~/UserControl1.ascx" %>
例如,您可以按照以下步骤操作:
创建一个新的 web 项目并将其命名为
WebUserControls
添加一个 Web Forms User Control 并将其命名为
UserControl1
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs" Inherits="WebUserControls.UserControl1" %> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
并在后面的代码中添加:
public string Text { get { return TextBox1.Text; } set { TextBox1.Text = value; } }
在使用者项目中,添加对包含
ascx
用户控件的项目的引用。将控件的
.ascx
文件复制到消费者项目中。注意:您不需要将文件添加到项目中,但物理文件应该存在于您在注册标签时用作
Src
的路径中.在要使用控件的页面中,添加:
<%@ Register TagPrefix="uc" TagName="UserControl1" Src="~/UserControl1.ascx" %>
以这种方式使用控件:
<uc:UserControl1 runat="server" Text="UserControl1" />
注意
如果您不想复制 ascx 文件,您可以使用不依赖于
ascx
文件的 Web Forms Server Control。然后为了使用这些自定义控件,注册它们就足够了:<%@ Register Assembly="WebUserControls" Namespace="WebUserControls" TagPrefix="uc" %>
- 此答案依赖于 Scott Guthrie 在该主题中的一篇精彩帖子:Creating and Using User Control Libraries
关于c# - 不同项目中的 Web 用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39610034/