[英]Loading user controls dynamically
How to load a user control dynamically in a page? 如何在页面中动态加载用户控件?
I have a page that contains radioButtons. 我有一个包含radioButtons的页面。 Each click on a radio button loads a user control (.ascx) in the page.
每次单击单选按钮都会在页面中加载用户控件(.ascx)。
What I am doing is loading all controls at the same time, but set their visibility to false. 我正在做的是同时加载所有控件,但将其可见性设置为false。 When a user clicks a radiobutton I set the visibility of the specific user control to true.
当用户单击radiobutton时,我将特定用户控件的可见性设置为true。
As a result I am loading all the user controls on each postback. 因此,我在每个回发上加载所有用户控件。
Is there any other possible way of doing this? 还有其他可能的方法吗?
Add a div with runat server on the page with an id "divControls" for example. 例如,在页面上添加一个带有runat服务器的div,其id为“divControls”。
Asp allow you to load a user control ".ascx" dynamically. Asp允许您动态加载用户控件“.ascx”。
The below code should solve your problem. 以下代码应该可以解决您的问题。
Control ctrl = Page.LoadControl("UserControlPath");
divControls.Controls.Clear();
divControls.Controls.Add(ctrl);
Is there any specific reasons to hold the usercontrols in a single page? 是否有任何具体原因将用户控件保存在单个页面中?
Think about the page view state as you are loading all the controls and setting it's visibility. 在加载所有控件并设置其可见性时,请考虑页面视图状态。
I think there are two possible solutions: 我认为有两种可能的解决方案:
Either create seprate page hosting different user control and when user click on the certain radio button, redirect to the respective page. 创建托管页面托管不同的用户控件,当用户单击某个单选按钮时,重定向到相应的页面。
Load on demand ie when user request a user control, only then load it but removing all other loaded user controls and hence page will have only one user control at any time. 按需加载,即当用户请求用户控件时,只加载它但删除所有其他加载的用户控件,因此页面随时只有一个用户控件。
If you don't keep them in a List, and that list in session, you'll have lots of trouble. 如果你没有将它们保存在列表中,并且在会话中列出该列表,那么你将遇到很多麻烦。
Ghyath's way is the right way but you should also add them to a List. Ghyath的方式是正确的方式,但你也应该将它们添加到List。
List<Object> Usercontrols = new List<Objects>{};
Control ctrl = Page.LoadControl("UserControlPath");
Usercontrols.Add(ctrl);
Session["Usercontrols"] = Usercontrols;
On each postback, you need to reload your div with the controls in your List. 在每个回发中,您需要使用列表中的控件重新加载div。 Edit: I've corrected the last line.
编辑:我已经纠正了最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.