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
將UserControl生成Html代碼 (thanks to Jeffrey Zhao )
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.