Using Razor engine on strings - not views

2020-03-17 19:30发布

I'd like to use the Razor engine without view (cshtml) files, but on strings. I want to do it from within MVC, I've seen examples that use

new RazorViewEngine().Render

but I can't find the Render method, is it something from the older days of MVC?

I've also seen examples that use Razor.Parse, but I can't find it either - probably missing a reference (but it should be there if I'm using MVC already, right?)

Is it advisable at all to use Razor if all I need to do is inject 3-4 parameters into an HTML string? I think I'm a bit infatuated with MVC right now and might not be thinking straight. I'm planning to cache the HTML strings in memory and just pass-in models from DB.

Thank you

3条回答
The star\"
2楼-- · 2020-03-17 20:01

There is a RazorParser class with Parse method which takes TextReader as an input parameter. However whole System.Web.Razor.Parser namespace is marked as

This type/member supports the .NET Framework infrastructure and is not intended to be used directly from your code.

so you have to figure it out by yourself.

查看更多
倾城 Initia
3楼-- · 2020-03-17 20:17

In order to use the RazorEngine to parse strings, you will need the RazorEngine.dll, which can be downloaded from http://razorengine.codeplex.com/

To parse a string with the Razor engine just use the following example:

var model = new { Name = "Test" };
var template = "Hello @Model.Name";

var result = Razor.Parse(template, model);

As to whether or not it is advisable to use it for parsing a string, really depends on what you are using it for. If you think you are going to need the flexibility that Razor offers, I would recommend it, but it does come with a bit of a performance hit when comparing it to a standard string replace.

查看更多
beautiful°
4楼-- · 2020-03-17 20:18

You may take a look at RazorEngine.

查看更多
登录 后发表回答