6

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Kiwanax
  • 1,265
  • 1
  • 22
  • 41
  • Maybe this can help: http://akinyusufer.blogspot.in/2011/05/razor-render-mvc3-view-render-to-string.html – Wouter de Kort Apr 10 '13 at 18:51
  • Possibly same concern/answer as this: [ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action](http://stackoverflow.com/a/4344602/1036187) – rivarolle Apr 10 '13 at 19:45
  • possible duplicate of [ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action](http://stackoverflow.com/questions/4344533/asp-net-mvc-razor-how-to-render-a-razor-partial-views-html-inside-the-controll) – Jesse Webb Apr 10 '13 at 21:44
  • Solved with that post! Thank you all! – Kiwanax Apr 11 '13 at 14:13

1 Answers1

6

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 )

Community
  • 1
  • 1
Adam Tal
  • 5,911
  • 4
  • 29
  • 49