我有一大堆UserControl
对象(ascx
文件)在他们自己的小项目中。然后,我在两个项目中引用该项目:REST API(这是一个类库项目)和主网站。
我确信这在网站上很容易,只需使用Controls.Add
in any Panel
或 ASP.NET 控件都可以。
但是,API 又如何呢?有什么方法可以通过了解控件的类型来呈现该控件的 HTML?这渲染控制方法不会向编写器写入任何 HTML,因为控件的生命周期甚至还没有开始。
请记住,我在 Web 项目中没有控件,因此我没有指向该项目的虚拟路径ascx
文件。所以负载控制方法在这里不起作用。
所有控件实际上都派生自同一个基本控件。在这个基类中我可以做些什么来允许我从一个全新的实例加载控件吗?
这是我最近所做的,效果很好,但是如果您在 ASP.NET 应用程序中使用它,则了解回发将不起作用。
[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)
{
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)