load a user control programmatically in to a html text writer(以编程方式将用户控件加载到 html 文本编写器中)
问题描述
我正在尝试将用户控件呈现为字符串.应用程序设置为允许用户使用令牌,并且用户控件在找到令牌的位置呈现.
I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
Control uc = LoadControl("~/includes/HomepageNews.ascx");
uc.RenderControl(writer);
return sb.ToString();
该代码呈现控件,但在控件的 Page_Load 中调用的所有事件均未触发.控件中有一个中继器需要触发.
推荐答案
很长一段时间以来,我一直在使用 Scott Guthrie 在他的博客中提供的以下代码:
I've been using the following code provided by Scott Guthrie in his blog for quite some time:
public class ViewManager
{
public static string RenderView(string path, object data)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl) pageHolder.LoadControl(path);
if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");
if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("ViewFile: " + path + "has no data property");
}
}
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, result, false);
return result.ToString();
}
}
object data 参数,可将数据动态加载到用户控件中,并可用于通过数组或类似的方式将多个变量注入到控件中.
The object data parameter, enables dynamic loading of data into the user control, and can be used to inject more than one variable into the control via an array or somethin similar.
此代码将触发控件中的所有正常事件.
This code will fire all the normal events in the control.
你可以在这里阅读更多信息
问候杰斯珀·豪格
这篇关于以编程方式将用户控件加载到 html 文本编写器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以编程方式将用户控件加载到 html 文本编写器中
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
