views:

336

answers:

1

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

+1  A: 

Your example could be implemented. But it violates the MVC pattern quite a bit. And if you are doing that anyway you might just as well go with the exact same solution you had in webforms.

When I create html mails I usually create a normal mvc view (with a action on some controller and a view). Then I render that view into a string and send it away. This way you are following the mvc pattern and you get the ability to see the mail in the browser automatically (you can just visit the url to that action. This can of course be restricted in any way you want).

To render a view to a string I use this class:

public class ViewRenderer
{
    protected RouteCollection RouteCollection { get; private set; }

    public DefaultViewRenderer()
        : this(RouteTable.Routes)
    {

    }

    public DefaultViewRenderer(RouteCollection routeCollection)
    {
        RouteCollection = routeCollection;
    }

    public virtual string RenderViewAsString<TController>(Expression<Action<TController>> action)
        where TController : Controller
    {
        var sb = new StringBuilder();
        var memWriter = new StringWriter(sb);

        var fakeContext = CreateFakeContext(memWriter);

        var oldContext = HttpContext.Current;
        HttpContext.Current = fakeContext;

        CreateHtmlHelper(fakeContext).RenderAction(action);

        HttpContext.Current = oldContext;

        memWriter.Flush();
        memWriter.Dispose();
        return sb.ToString();
    }

    protected virtual HttpContext CreateFakeContext(StringWriter memWriter)
    {
        var fakeResponse = new HttpResponse(memWriter);
        var context = new HttpContext(HttpContext.Current.Request, fakeResponse);

        foreach (var key in HttpContext.Current.Items.Keys)
            context.Items[key] = HttpContext.Current.Items[key];

        foreach (string key in HttpContext.Current.Session.Keys)
            context.Session[key] = HttpContext.Current.Session[key];

        return context;
    }

    protected virtual HtmlHelper CreateHtmlHelper(HttpContext fakeContext)
    {
        var fakeControllerContext = CreateControllerContext(fakeContext, RouteCollection);
        return new HtmlHelper(new ViewContext(fakeControllerContext,
                                                  new FakeView(), new ViewDataDictionary(), new TempDataDictionary()), new FakePage());
    }

    protected virtual ControllerContext CreateControllerContext(HttpContext fakeContext, RouteCollection routeCollection)
    {
        return new ControllerContext(
            new HttpContextWrapper(fakeContext),
            routeCollection.GetRouteData(new HttpContextWrapper(HttpContext.Current)), new FakeController());
    }

    protected class FakeView : IView
    {
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            throw new NotImplementedException();
        }
    }

    protected class FakeController : Controller
    {

    }

    protected class FakePage : IViewDataContainer
    {
        public ViewDataDictionary ViewData
        {
            get { return new ViewDataDictionary(); }
            set { }
        }
    }
}

This uses a fake response that writes the result of the view into a stringbuilder. Then you use this like this:

var viewRenderer = new ViewRenderer();
var body = viewRenderer.RenderViewAsString<SomeController>(x => x.ActionThatRendersHtmlMail(parameters));

Then you just send the mail with that body text. You can of course wrap this in you own class so you can call EmailTemplate.SubscriptionEmail(); (from your example).

Mattias Jakobsson