views:

139

answers:

3

Hi,

Would it be a good idea, and executable, to use the ASP.NET MVC View Engine to render html to be sent out by email?

I know it's possible to let the view render into a string. So that could be use to build the mail message. Since ASP.NET MVC is already used in the application, I get to use all practical ASP.NET MVC stuff without having to use Brail or NVelocity for my "mail views".

Good idea? Any caveats? Examples :) ?

+1  A: 

Yes it is a good idea and relatively easy to implement.

Darin Dimitrov
Bertvan
In this case you could perform this in a new thread or using an AsyncController.
Darin Dimitrov
Okay, let's see if this will work :)
Bertvan
+1  A: 

I personally think it's a good idea. Definitely better than putting a piece of markup with placeholders into the database.

The disadvantage is that you will need Visual Studio to edit those templates then recompile and redeploy the project. You wouldn't be able to "outsource" working with templates to other non-technical staff.

And yes, adding new templates would also require your personal intervention.

Developer Art
Recompiling is indeed the biggest caveat. Which is also why, we're stepping away from this approach and start looking at XSLT...
Bertvan
+1  A: 

Here,s my version of the RenderPartialToString as an extension method (which also takes care of paths etc..):

public static class ExtensionMethods
{
    public static string RenderPartialToString(this ControllerBase controller, string partialName, object model)
    {
        var vd = new ViewDataDictionary(controller.ViewData);
        var vp = new ViewPage
        {
            ViewData = vd,
            ViewContext = new ViewContext(),
            Url = new UrlHelper(controller.ControllerContext.RequestContext)
        };

        ViewEngineResult result = ViewEngines
                                  .Engines
                                  .FindPartialView(controller.ControllerContext, partialName);

        if (result.View == null)
        {
            throw new InvalidOperationException(
            string.Format("The partial view '{0}' could not be found", partialName));
        }
        var partialPath = ((WebFormView)result.View).ViewPath;

        vp.ViewData.Model = model;

        Control control = vp.LoadControl(partialPath);
        vp.Controls.Add(control);

        var sb = new StringBuilder();

        using (var sw = new StringWriter(sb))
        {
            using (var tw = new HtmlTextWriter(sw))
            {
                vp.RenderControl(tw);
            }
        }
        return sb.ToString();
    }
}

usage:

return this.RenderPartialToString("YourPartialView", yourModel);

hope this helps..

jim

jim