Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send PartialView content as email

I have a PartialView that contains a HTML code with Razor annotations. It generates to me a page that I want to send by email to anyone. Is there a way to translate this PartialView into HTML content to send it?

like image 503
Kiwanax Avatar asked Apr 10 '13 18:04

Kiwanax


1 Answers

I would suggest using MvcMailer which does exactly what you want (without you having to write the code for it.. it can also do it asynchronously):

https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide

Update

As stated at the comments, the solution for implementing it yourself (I still think MvcMailer will make your life easier):

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

( ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action )

like image 60
Adam Tal Avatar answered Sep 22 '22 19:09

Adam Tal