问题描述
||
我有一个“ 0”,允许用户上传文件,并以“ 1”显示它们。在父页面上,我有一个jQuery标签控件,向其中动态添加了
UserControl
的2个实例(在不同的标签上)。第二个实例工作正常,所以我知道控件可以工作。但是,当我尝试使用第一个实例上传文件时,正在引用第二个实例...因此所有属性值,控件名称等都指向第二个实例。
这就是我在隐藏代码的父页面中加载控件的方式:
protected void Page_Load(object sender,EventArgs e)
{
MyControl ucAttachments1 = (MyControl) Page.LoadControl(\"~/controls/mycontrol.ascx\");
ucAttachments1.ID = \"ucAttachments1\";
ucAttachments1.Directory = \"/uploads/documents\";
ucAttachments1.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachments1.Controls.Add(ucAttachments1);
MyControl ucAttachments2 = (MyControl)Page.LoadControl(\"~/controls/mycontrol.ascx\");
ucAttachments2.ID = \"ucAttachments2\";
ucAttachments2.Directory = \"/uploads/drawings\";
ucAttachments2.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachmetns2.Controls.Add(ucAttachments2);
}
在html中:
<div id=\"tabContainer\">
<div id=\"files\">
<asp:PlaceHolder id=\"phAttachments1\" runat=\"server\" />
</div>
<div id=\"drawings\">
<asp:PlaceHolder id=\"phAttachments2\" runat=\"server\" />
</div>
</div>
用户控制代码段:
private string directory;
override protected void OnLoad(EventArgs e)
{
PopulateAttachmentGridview();
}
protected btnUpload_Click(object sender,EventArgs e)
{
UploadFile(directory);
}
public string Directory
{
get { return directory; }
set { directory = value; }
}
如何确保正确引用我的用户控件?
解决方法
检查呈现给客户端的实际html和javascript,以确保没有与重复出现的控件相关的重复ID。
, 我认为这是问题所在
MyControl ucAttachments1 = (MyControl) Page.LoadControl(\"~/controls/mycontrol.ascx\");
MyControl ucAttachments2 = (MyControl)Page.LoadControl(\"~/controls/mycontrol.ascx\");
您将控件的同一实例引用到两个不同的变量。因此,现在您具有相同实例的两个不同引用,因为现在您最后设置了\“ ucAttachments2 \”的属性,所以发生的事情是您的实例上设置了第二个控件属性。因此,无论何时尝试访问该实例实例(通过使用\“ ucAttachments1 \”或\“ ucAttachments2 \”),您将获得第二个控件的属性。
尝试做:
MyControl ucAttachments1 = new MyControl();
ucAttachments1 = (MyControl) Page.LoadControl(\"~/controls/mycontrol.ascx\");
ucAttachments1.ID = \"ucAttachments1\";
ucAttachments1.Directory = \"/uploads/documents\";
ucAttachments1.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachments1.Controls.Add(ucAttachments1);
MyControl ucAttachments2 = new MyControl();
ucAttachments2 = (MyControl) Page.LoadControl(\"~/controls/mycontrol.ascx\");
ucAttachments2.ID = \"ucAttachments2\";
ucAttachments2.Directory = \"/uploads/drawings\";
ucAttachments2.DataChanged += new MyControl.DataChangedEventHandler(DoSomething);
phAttachmetns2.Controls.Add(ucAttachments2);