无法识别ASP.net用户控件

本文关键字:用户 控件 net ASP 识别 | 更新日期: 2023-09-27 18:11:32

我正在尝试动态添加一个用户控件到asp.net网页。用户控制代码:

<%@ Control ClassName="CustomParameterView" %>
<script runat="server">
    public string Value { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }
    private void Input_OnTextChanged(object sender, EventArgs e)
    {
        Value = Input.Text;
    }
</script>
<div class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-2 control-label" id="DisplayName"></label>
        <div class="col-sm-3">
            <asp:TextBox ID="Input" runat="server" CssClass="form-control" OnTextChanged="Input_OnTextChanged" />
        </div>
    </div>
</div>

我已经在.aspx文件中添加了注册行:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PerCHW.Valkyrie.Server.WebApplication._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <%@ Reference Control="CustomParameterView.ascx" %>
...

问题是:

  var control = (CustomParameterView) LoadControl("CustomParameterView.ascx");

不能编译。

我也看到有人试图在UC名称之前添加ASP.,但这不起作用…

我做错了什么?

无法识别ASP.net用户控件

看起来您没有将控件添加到占位符。

在.aspx页面添加一个占位符:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

然后将控件添加到

后面代码中的占位符中
var control = (CustomParameterView)LoadControl("~/CustomParameterView.ascx");
PlaceHolder1.Controls.Add(control);

确保每次加载页面时都调用此代码,因此不要将其放在!IsPostBack检查中,否则控件将在PostBack后消失。