Submit Your Site For Free!

Email Address:
* URL:
*
*Indicates Mandatory Field

Terms & Conditions

DevWebProUK
FlashNewz
DevWebPro






ASP.NET - Load User Controls From An HttpHandler

By Mads Kristensen
Expert Author
Article Date: 2007-09-19

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.

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);


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

About the Author:
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/



Newsletter Archive | Submit Article | Advertising Information | About Us | Contact

DevWebProUK is an iEntry, Inc.® publication - 1998-2008 All Rights Reserved Privacy Policy and Legal