与服务器控件的页面使用LoadControl [英] Using LoadControl on pages with server controls
问题描述
我试图创造,我可以作为邮件发送的用户控件模板。
I'm trying to create a user control template that I can send as email.
在一个工具类我有一个包含此code的方法:
In a utility class I have a method that contains this code:
StringBuilder sb = new StringBuilder();
Page p = new Page();
UserControl ctrl = (UserControl)p.LoadControl("~/EmailTemplates/OrderConfirmation.ascx");
StringWriter sw = new StringWriter(sb);
Html32TextWriter htw = new Html32TextWriter(sw);
ctrl.RenderControl(htw);
这正确写入用户控件的文字,但如果我想使用一个服务器控件,如控制页面内的一个列表视图,列表视图不会求。似乎只有直列code块进行评估。我怎样才能解决这个得到什么?
This correctly writes the user controls text, but if I want to use a server control such as a listview inside of the controls page, the listview is never evaluated. It seems that only inline code blocks are evaluated. How can I get around this?
推荐答案
您实际上应该将控件添加到一个页面,执行该页面:
You should actually add the control to a page and execute the page:
var page = new FormlessPage();
var ctrl = (UserControl)page.LoadControl("~/EmailTemplates/OrderConfirmation.ascx");
page.Controls.Add(ctl);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
无形页只是看起来像:
Formless page simply looks like:
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
它可以让你的控制有没有输入元素的<形式的方式>
包装
此方法将调用你的页面生命周期方法,并很好地结合你的表单元素。
This method will call your page lifecycle methods and bind up your form elements nicely.
这篇关于与服务器控件的页面使用LoadControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!