我在他们自己的小项目中有很多 UserControl
对象(ascx
文件)。然后我在两个项目中引用这个项目:REST API(这是一个类库项目)和主网站。
我相信这在网站上很容易,只需在任何 Panel
或 ASP.NET 控件中使用 Controls.Add
即可。
但是,API 呢?有什么方法可以通过知道控件的类型来呈现此控件的 HTML? RenderControl方法不会将任何 HTML 写入编写器,因为控件的生命周期甚至还没有开始。
请记住,我在 Web 项目中没有控件,所以我没有 ascx
文件的虚拟路径。所以 LoadControl方法在这里不起作用。
所有控件实际上都派生自同一个基本控件。我可以在这个基类中做些什么来让我从一个全新的实例加载控件吗?
最佳答案
这是我最近所做的,效果很好,但如果您在 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)
{
}
}
关于c# - 以编程方式呈现 Web UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088427/