Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a Razor view to a string?

I would like to use my Razor view as some kind of template for sending emails, so I would like to "save" my template in a view, read it into controller as a string, do some necessary replacements, and then send it.

I have solution that works: my template is hosted somewhere as an HTML page, but I would like to put it into my application (i.e. in my view). I don't know how to read a view as a string in my controller.

like image 431
Vlado Pandžić Avatar asked Mar 12 '13 20:03

Vlado Pandžić


People also ask

How do I render a razor view to string?

Listing 1: Rendering a Razor View to String from within a Controller. The RenderViewToString() method works by receiving a controller context and virtual view path (i.e., ~/views/item/page. cshtml ) and optional model data that are passed to the view.

How do I return a rendered Razor view from Web API controller?

ASP.NET MVC4 Web API controller should return Razor view as html in json result property. Message=The method or operation is not implemented. var viewResult = ViewEngines.

What is razor Cshtml?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.


2 Answers

I use the following. Put it on your base controller if you have one, that way you can access it in all controllers.

public static string RenderPartialToString(Controller controller, string viewName, object model)
{
    controller.ViewData.Model = model;

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

        return sw.GetStringBuilder().ToString();
    }
}
like image 65
mattytommo Avatar answered Sep 25 '22 17:09

mattytommo


Take a look at the RazorEngine library, which does exactly what you want. I've used it before for email templates, and it works great.

You can just do something like this:

// Read in your template from anywhere (database, file system, etc.)
var bodyTemplate = GetEmailBodyTemplate();

// Substitute variables using Razor
var model = new { Name = "John Doe", OtherVar = "Hello!" };
var emailBody = Razor.Parse(bodytemplate, model);

// Send email
SendEmail(address, emailBody);
like image 35
Garrett Vlieger Avatar answered Sep 25 '22 17:09

Garrett Vlieger