In the past I've used UserControls to create email templates which I can fill properties on and then use LoadControl and then RenderControl to get the html for which to use for the body text of my email. This was within asp.net webforms.
I'm in the throws of building an mvc website and wanted to do something similar. I've actually considered putting this functionality in a seperate class library and am looking into how I can do this so that in my web layer I can just call EmailTemplate.SubscriptionEmail() which will then generate the html from my template with properties in relevant places (obviously there needs to be parameters for email address etc in there).
I wanted to create a single Render control method for which I can pass a string to the
path of the UserControl which is my template. I've come across this on the web that kind of suits my needs:
public static string RenderUserControl(string
path,
string propertyName, object propertyValue)
{
Page pageHolder = new Page();
UserControl viewControl =
(UserControl)pageHolder.LoadControl(path);
if (propertyValue != null)
{
Type viewControlType = viewControl.GetType();
PropertyInfo property = viewControlType.GetProperty(propertyName);
if (property != null)
property.SetValue(viewControl, propertyValue, null);
else
{
throw new Exception(string.Format(
"UserControl: {0} does not have a public {1} property.",
path, propertyName));
}
}
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
My issue is that my UserControl(s) may have multiple and differing properties. So SubscribeEmail may require FirstName and EmailAddress where another email template UserControl (lets call it DummyEmail) would require FirstName, EmailAddress and DateOfBirth.
The method above only appears to carry one parameter for propertyName and propertyValue. I considered an array of strings that I could put the varying properties into but then I thought it'd be cool to have an object intialiser so I could call the method like this:
RenderUserControl("EmailTemplates/SubscribeEmail.ascs", new object() { Firstname="Lloyd", Email="
[email protected]" })
Does that make sense? I was just wondering if this is at all possible in the first place and how I'd implement it? I'm not sure if it would be possible to map the properties set on 'object' to properties on the loaded user control and if it is possible where to start in doing this?
Has anyone done something like this before? Can anyone help?
Lloyd