C# 使用asp.net中未显示的参数动态加载的用户控件
我搜索了很多关于这个问题的信息,但是什么都没有找到 我的问题如下:我有一个主视图,当我单击按钮时,我想在其中加载一个带有参数的用户控件,但用户控件不会显示。调用用户控件的构造函数并设置参数,甚至调用来自用户控件的页面加载事件。我做错了什么C# 使用asp.net中未显示的参数动态加载的用户控件,c#,asp.net,user-controls,C#,Asp.net,User Controls,我搜索了很多关于这个问题的信息,但是什么都没有找到 我的问题如下:我有一个主视图,当我单击按钮时,我想在其中加载一个带有参数的用户控件,但用户控件不会显示。调用用户控件的构造函数并设置参数,甚至调用来自用户控件的页面加载事件。我做错了什么 Main.aspx: <%@ Page Title="Main page" Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="MainApp.Main"
Main.aspx
:
<%@ Page Title="Main page" Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="MainApp.Main" MasterPageFile="~/Site.master" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<%-- some other fields which i send to the user control on click --%>
<div class="col-lg-1 col-sm-12 col-md-1">
<asp:Button runat="server" CssClass="btn btn-primary" CausesValidation="false" ID="generateData" OnClick="generateData_Click" Text="View info" />
</div>
<div runat="server" id="contentDiv">
<p>No info available atm.</p>
</div>
</asp:Content>
UserControl1.aspx.cs
:
public partial class UserControl1: System.Web.UI.UserControl
{
public string Param3 { get; set; }
public string Param1 { get; set; }
public string Param2 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
public UserControl1(string param1, string param2, string param3)
{
Param1 = param1;
Param2 = param2;
Param3 = param3;
}
}
UserControl1.ascx
:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs" Inherits="MainApp.UserControls.UserControl1" %>
<div>
<p style="color: red">Under construction</p>
</div>
下面是第二个按类型加载控件的方法不起作用的原因的完整解释: 存在差异的原因是,在第二种情况下 正在绕过两个分部类的绑定机制 当您将ascx控件作为常规声明包含在页面中时, 其中声明的控件(示例中的标签)是 在类被创建时由框架自动实例化 实例化。这是一种“前端”绑定机制 ascx文件并实例化类中的对象 当您使用LoadControl(字符串)时,您的操作完全相同 事情它使用虚拟路径来获取“前端”文件并确保 其中的控件被实例化 但是,当您使用新的(to 2.0)LoadControl(类型、对象)时 版本中,没有可用的虚拟路径,因此它不会 假设(因为它无法确保类型具有前端文件)
请看一下@BikashSinghMaharjan,它正在工作,但是为什么要使用一些额外的方法而不是内置的功能呢?谢谢你的解释。微软添加了一个无法按预期使用的方法,这似乎很奇怪。。
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs" Inherits="MainApp.UserControls.UserControl1" %>
<div>
<p style="color: red">Under construction</p>
</div>
UserControl1 uc = (UserControl1)this.LoadControl("~/UserControls/UserControl1.ascx");
uc.Param1 = "val1";
...