以编程方式呈现Web UserControl [英] Programmatically rendering a web UserControl
问题描述
我在自己的小项目中加载了 UserControl
个对象( ascx
文件).然后,我在两个项目中引用该项目:REST API(这是一个类库项目)和主网站.
I have a load of UserControl
objects (ascx
files) in their own little project. I then reference this project in two projects: The REST API (which is a class library project) and the main website.
我确信这在网站上会很容易,只需在任何 Panel
中使用 Controls.Add
即可,否则ASP.NET控件都可以使用.
I'm sure this would be easy in the website, simply use Controls.Add
in any Panel
or ASP.NET control would work.
但是,API呢?仅通过了解控件的类型,有什么方法可以呈现此控件的HTML? RenderControl 方法未编写由于控件的生命周期还没有开始,因此没有任何写给作者的HTML.
However, what about the API? Is there any way I can render the HTML of this control, simply by knowing the type of the control? The RenderControl method doesn't write any HTML to the writer as the control's life cycle hasn't even started.
请记住,我在Web项目中没有控件,因此我没有指向 ascx
文件的虚拟路径.因此, LoadControl 方法在这里不起作用.
Please bare in mind that I don't have the controls in the web project, so I don't have a virtual path to the ascx
file. So the LoadControl method won't work here.
所有控件实际上都来自同一基本控件.在这个基类中我可以做些什么,让我可以从一个全新的实例中加载控件?
All the controls actually derive from the same base control. Is there anything I can do from within this base class that will allow me to load the control from a completely new instance?
推荐答案
这是我最近所做的,效果很好,但是了解如果在ASP.NET应用程序中使用回发功能,则回发将不起作用.
This is what I have done recently, works well, but understand postbacks will not work if you use it inside your ASP.NET app.
[WebMethod]
public static string GetMyUserControlHtml()
{
return RenderUserControl("Com.YourNameSpace.UI", "YourControlName");
}
public static string RenderUserControl(string assembly,
string controlName)
{
FormlessPage pageHolder =
new FormlessPage() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath }; //allow for "~/" paths to resolve
dynamic control = null;
//assembly = "Com.YourNameSpace.UI"; //example
//controlName = "YourCustomControl"
string fullyQaulifiedAssemblyPath = string.Format("{0}.{1},{0}", assembly, controlName);
Type type = Type.GetType(fullyQaulifiedAssemblyPath);
if (type != null)
{
control = pageHolder.LoadControl(type, null);
control.Bla1 = "test"; //bypass compile time checks on property setters if needed
control.Blas2 = true;
}
pageHolder.Controls.Add(control);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
这篇关于以编程方式呈现Web UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!