将UserControl生成Html代码 (thanks to Jeffrey Zhao )
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.UI;
6using System.IO;
7using System.Web.UI.HtmlControls;
8using System.Reflection;
9
10/// <summary>
11///UserControlRender 的摘要说明
12/// </summary>
13namespace System.Web.UI
14{
15 public class UserControlRender
16 {
17 private Page _thisPage;
18 public UserControlRender()
19 {
20 //
21 //TODO: 在此处添加构造函数逻辑
22 //
23 }
24
25 /// <summary>
26 /// 加载指定虑拟路径控件
27 /// </summary>
28 /// <param name="path">控件路径</param>
29 /// <returns>返回控件对象</returns>
30 private UserControl LoadUserControl(string path)
31 {
32 _thisPage = new MyPage();
33 Control control = _thisPage.LoadControl(path);
34 return (UserControl)control;
35 }
36
37 /// <summary>
38 /// 渲染用户控件并生成代码
39 /// </summary>
40 /// <param name="control">目标控件对象</param>
41 /// <returns></returns>
42 private string RenderControlView(UserControl control)
43 {
44 AddRangeMark(control);
45
46 StringWriter writer = new StringWriter();
47 this._thisPage.Form.Controls.Add(control);
48 this._thisPage.Server.Execute(this._thisPage, writer, false);
49
50 return RemoveMarkFromControlText(writer.ToString());
51 }
52
53 /// <summary>
54 /// 为用户控件内容头尾打上标记
55 /// </summary>
56 /// <param name="control">要渲染的控件</param>
57 private void AddRangeMark(UserControl control)
58 {
59 LiteralControl liStart = new LiteralControl();
60 LiteralControl liEnd = new LiteralControl();
61
62 liStart.Text = "<start/>";
63 liEnd.Text = "<end/>";
64
65 control.Controls.AddAt(0, liStart);
66 control.Controls.Add(liEnd);
67 }
68
69 /// <summary>
70 /// 将生成的字符串中开始和结束标记去除
71 /// </summary>
72 /// <param name="content">控件生成的代码</param>
73 /// <returns>去除了开始结束标记后的代码</returns>
74 private string RemoveMarkFromControlText(string content)
75 {
76 content = content.Substring(content.IndexOf("<start/>") + 9);
77 content = content.Substring(0, content.IndexOf("<end/>"));
78 return content;
79 }
80
81 public string RenderControlView(string path)
82 {
83 return RenderControlView(LoadUserControl(path));
84 }
85 }
86
87 public class MyPage : Page
88 {
89 HtmlForm form;
90 public MyPage()
91 {
92 if (this.Form == null)
93 {
94 form = new HtmlForm();
95 this.Controls.Add(form);
96 foreach (MemberInfo item in typeof(Page).FindMembers(MemberTypes.Field, BindingFlags.NonPublic | BindingFlags.Instance, null, null))//查找Page中的_form字段,并将创建的form对象赋值给它
97 {
98 if (item.Name == "_form")
99 {
100 ((FieldInfo)item).SetValue(this, form);
101 break;
102 }
103 }
104 }
105 else
106 {
107 form = this.Form;
108 }
109 }
110
111 }
112}
113