ASP.net用户控件无法识别

时间:2016-10-05 10:54:27

标签: c# asp.net user-controls

我正在尝试将用户控件动态添加到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.,但这不起作用......

我做错了什么?

1 个答案:

答案 0 :(得分:2)

看起来您没有将控件添加到PlaceHolder。

在.aspx页面中添加PlaceHolder:

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

然后在后面的代码中将Control添加到PlaceHolder:

var control = (CustomParameterView)LoadControl("~/CustomParameterView.ascx");
PlaceHolder1.Controls.Add(control);

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