However, Razor is still primarily focused on generating xml-like markup (e.g. HTML) in the sense that the Razor parser uses the presence of <tags> to determine the transition between code and markup. You can probably use it to generate any text but you might run into issues when your output doesn't match Razor's assumptions about what your intentions are.
So for example while this is valid Razor code (because of the <div> tag):
@if(printHello) {
<div>Hello!</div>
}
The following snippet is invalid (because the Hello! is still being treated as code):
@if(printHello) {
Hello!
}
However there's a special <text> tag that can be used to force a transition for multi-line blocks (the <text> tag will not be rendered):
@if(printHello) {
<text>Hello!
Another line</text>
}
There is also a shorter syntax to force a single line to transition using @::
Both RazorEngine and RazorTemplates are already mentioned here, but check out RazorMachine. You can simply point your non-MVC app to a ~/Views folder of (another) existing MVC app, execute with sending proper model and get rendered output on 2 lines of code:
var sb = new StringBuilder();
//RazorMachine magic:
//*tweets* is basically List<TwitterPost> - simple collection of custom POCO
//first param for rm.ExecuteUrl points to ~/Views folder, MVC style
var rm = new RazorMachine(htmlEncode: false);
ITemplate template = rm.ExecuteUrl("~/twitter/twitter", tweets);
//do whatever you want with result
sb.Append(template);
using Razor.Templating.Core;
var model = new ExampleModel()
{
PlainText = "This text is rendered from Razor Views using Razor.Templating.Core",
HtmlContent = "<em>You can use it to generate email content, report generation and so on</em>"
};
// Both ViewBag and ViewData should be added to the same dictionary.
var viewDataOrViewBag = new Dictionary<string, object>();
// ViewData is same as mvc
viewDataOrViewBag["Value1"] = "1";
// ViewBag.Value2 can be written as below. There's no change on how it's accessed in .cshtml file
viewDataOrViewBag["Value2"] = "2";
var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);