Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Jun 03, 2008 05:16 PM by null12345
Jun 03, 2008 09:26 AM|LINK
How do I render user control as string in a controller?
I don't want it to be rendered as a final browser output but just as a e-mail body content.
Jun 03, 2008 01:04 PM|LINK
Try something like this:
1 Type controlType = System.Web.Compilation.BuildManager.GetCompiledType(virtualPath);
2 System.Reflection.ConstructorInfo constructor = controlType.GetConstructor(Type.EmptyTypes);
3 Control control = (Control)constructor.Invoke(null);
5 System.Web.UI.Page page = new Page();
9 StringBuilder builder = new StringBuilder();
10 System.IO.StringWriter writer = new System.IO.StringWriter(builder);
11 utility.Execute(page, writer, true);
12 return builder.ToString();
virtualPath is the control path.
If you need to set properties on the control, you have to use reflection:
1 System.Reflection.PropertyInfo property = controlType.GetProperty(propertyName);
2 property.SetValue(control, data, null);
That's all [:)]
Jun 03, 2008 04:07 PM|LINK
What's utility in line 11?
Jun 03, 2008 04:18 PM|LINK
That's the HttpServerUtility. In the controller, you have it directly in "this.Server".
Jun 03, 2008 05:16 PM|LINK
Thanks for the answer. However I hope the team will make other easy solution as this is a quite common scenario I think.