Kyle W
Kyle W

Reputation: 3752

Create razor view without web

We're currently using a product to send emails, and are doing so from a number of executables that run periodically. This product has very limited processing of dynamic data, so if we want a table from a list, we have to create the table in our C# code and send the HTML as a single variable, which causes us to have HTML in our config file.

A coworker saw this type of thing and thought we might be able to use it. So I'm trying to develop a proof-of-concept of creating a view in an executables and converting it to a string (we would then develop our emails outside of the emailing product and send the whole thing in as a single string.

My questions are:

1) Is there a better way of doing this? Bringing in the MVC framework certainly isn't what it's intended for. If there's another product out there that will do what we want (allow us to easily create a dynamic email) that is easy to use and more suited, that would be great.

2) Should I just fake out all the data? If I create fake http context and all that jazz, I can get it to do what I want.

3) Is there an easier way to convert a view to a string, based on a ViewModel?

Upvotes: 0

Views: 253

Answers (1)

Filip W
Filip W

Reputation: 27187

If you don't need HTTP to be involved at all, you can simply run Razor engine from C# directly using RazorEngine project - there is a great project that allows you to do so - https://github.com/Antaris/RazorEngine.

It allows you to use Razor as general purpose templating engine (rather than something MVC-specific).

Simple example from GitHub:

string template = "Hello @Model.Name, welcome to RazorEngine!";
string result = Razor.Parse(template, new { Name = "World" });

Alternatively, if you still want that to be accessible via HTTP, you could do this relatively easy with ASP.NET Web API, in a very lightweight manner - without having to worry about ASP.NET whatsoever (since you can even self host that).

WebApiContrib has a Razor view formatter already available - https://github.com/WebApiContrib/WebApiContrib.Formatting.RazorViewEngine

Upvotes: 3

Related Questions