michasaucer
michasaucer

Reputation: 5228

Render Razor View Page as string from WebApi Core

I have mock cshtml that looks like this:

@model TaskManager.Models.ViewModels.ProjectRaportViewModel

@{
    var name = Model.Project.Name;

    <h3>@name</h3>
}
<br />
<4h>Hello World!</4h>

I want to return that view(or any) as string but as html rendered by Razor (so i think, razor will change C# things to html tags etc).

I have a controller that looks like this:

    [HttpGet("{projectId}")]
    public IActionResult GetRaportFromProject([FromRoute] int projectId)
    {
        var html = this.pdfService.RenderViewToHtml(projectId);
        return this.Content(html, "text/html", Encoding.UTF8);
    }

And in pdfService i have this method:

    public string RenderViewToHtml(int projectId)
    {
        this.projectService.GetItem(projectId);

        var raportHtml = what to do next?                   
    }

My question is, how to render cshtml to html by Razor in service class and then return it as string from WebApi endpoint?

Upvotes: 1

Views: 1876

Answers (1)

Petyo Zhechev
Petyo Zhechev

Reputation: 74

If you use .Net Core, there is a NuGet package you can easily install: RazorEngine.NetCore

The documentation is good but here is the short version:

Include the library:

    using RazorEngine;
    using RazorEngine.Templating;

Get your razor html

        string razorView= "Hello @Model.Name, welcome to RazorEngine!";

If it's in a file you could use File.ReadAllText

        string razorView = await File.ReadAllTextAsync(filePath);

and compile:

string result = Engine.Razor.RunCompile(razorView, "templateKey", null, null);

And if you want to inject some object, pass it in the 4th argument

Upvotes: 3

Related Questions