A (less) simple include for ASP.NET
In yesterday’s post, I published the code for a simple include method for ASP.NET that I’ve been using in a couple of places, only to realize that it was fine for what I was doing but probably not very useful beyond that.
So I spent some time today broadening its scope. It now supports nested includes (I modified the original post to reflect that change) and also setting properties on the control.
You can still do plain includes:
<% this.Include("contents.ascx"); %>
But now you can also set properties on the included user control using an anonymous object:
<% this.Include("contents.ascx", new {number=2, what="A"}); %>
The code for the helper considerably grew along the way but it’s still reasonable:
using System; using System.Linq; using System.Reflection; using System.Web.UI; public static class IncludeHelper { public static void Include(this TemplateControl host,
string virtualPath) { Include(host, virtualPath, null); } public static void Include(this TemplateControl host,
string virtualPath,
object properties) { var resolvedPath = host.ResolveUrl(virtualPath); var include = host.LoadControl(resolvedPath); if (properties != null) { var includeType = include.GetType(); foreach (var fieldInfo in
properties.GetType().GetProperties()) { var targetInfo = includeType.GetMember(
fieldInfo.Name, MemberTypes.Field |
MemberTypes.Property, BindingFlags.IgnoreCase |
BindingFlags.Instance |
BindingFlags.Public) .FirstOrDefault(); var targetPropertyInfo = targetInfo as PropertyInfo; if (targetPropertyInfo != null) { targetPropertyInfo.SetValue(
include,
fieldInfo.GetValue(properties, null),
null); } else { var targetFieldInfo = targetInfo as FieldInfo; if (targetFieldInfo != null) { targetFieldInfo.SetValue(
include,
fieldInfo.GetValue(properties, null)); } else { throw new ArgumentException( "There is no property of field with " +
"that name on the target control.", fieldInfo.Name); } } } } using (var writer =
new HtmlTextWriter(host.Page.Response.Output)) { include.RenderControl(writer); } } }
I hope this helps. Again, if you are OK with the regular syntax to include a user controls, you probably shouldn’t use this and stick to what you know. I built this because I’m not entirely satisfied with that syntax and because I have a clear use case where it makes more sense. Make your own opinion and follow it :)
Note: The control is still not going into the control tree, which breaks lots of stuff. I don't really care that much about it but it may be important to you so I thought I'd point it out.