Today I had what seemed to be an easy task of serving the rendered HTML of a user control through an Httphandler (.ashx). It’s something I’ve done many times before but never from an HttpHandler. If you want to do it from an .aspx page it is very easy. You just reference the user control and then the code-behind can access it in a strongly typed way when calling LoadControl("control.ascx").

An HttpHandler however does not have a LoadControl method and it doesn’t have a way of referencing user controls like a page does. What started as an easy task now turned into something unknown – reflection was needed.

The code

So, this is the method I came up with using reflection.

[code:c#]

System.Web.UI.Page page = new System.Web.UI.Page(); 
UserControl profile = (UserControl)page.LoadControl("~/controls/profile.ascx");

Type type = profile.GetType();
type.GetProperty("Name").SetValue(profile, "John Smith", null);
type.GetProperty("Age").SetValue(profile, 53, null);

[/code]

Notice that I use a fully qualified relative path to load the profile.ascx control. That is because if you pre-compile the web application it would fail otherwise. I don’t know if it’s a bug or not, but this is the way around it.

I don’t think the solution is very pretty, but it’s not ugly either. It’s short and precise and the reflection part is very transparent. No matter what, it solved the problem of loading user controls from an HttpHandler.

Comments


Comments are closed