如何使用 ASP.NET 中的参数呈现 UserControl
How to render UserControl with parameters in ASP.NET
我使用以下代码来渲染 UserControl
。
//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/path_to_control.ascx").RenderControl(h);
string controlAsString = b.ToString();
但我想传递给 UserControl
一些 参数 因此它应该在渲染之前获取数据并更新其属性 .
怎么做到的?
谢谢!
如回答here:
Just load the control using the path of the .ascx file, cast to proper type and set the properties one by one:
MyControl myControl = (MyControl )Page.LoadControl("~/path_to_control.ascx");
myControl.Param1= 1;
myControl.Param2= 2;
myControl.RenderControl(h)
或:
Page.LoadControl(typeof(MyControl), new object[] {1, 2}).RenderControl(h);
我使用以下代码来渲染 UserControl
。
//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/path_to_control.ascx").RenderControl(h);
string controlAsString = b.ToString();
但我想传递给 UserControl
一些 参数 因此它应该在渲染之前获取数据并更新其属性 .
怎么做到的? 谢谢!
如回答here:
Just load the control using the path of the .ascx file, cast to proper type and set the properties one by one:
MyControl myControl = (MyControl )Page.LoadControl("~/path_to_control.ascx");
myControl.Param1= 1;
myControl.Param2= 2;
myControl.RenderControl(h)
或:
Page.LoadControl(typeof(MyControl), new object[] {1, 2}).RenderControl(h);