Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Razor engine on strings - not views

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

like image 993
Madd0g Avatar asked Nov 21 '11 17:11

Madd0g


People also ask

How does a Razor view engine work?

The namespace for Razor Engine is System. Razor uses the "@" character instead of "<% %>" as used by the ASPX View Engine. The Razor file extension is "cshtml" for the C# language. By default, Razor View Engine encodes html tags or scripts before it's being rendered to view that avoids Cross-Site Scripting attacks.

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 view in C#?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language.

What is Htmlstring in MVC?

Methods. Create(String) Creates an HTML-encoded string using the specified text value. IsNullOrEmpty(MvcHtmlString) Determines whether the specified string contains content or is either null or empty.


2 Answers

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.

like image 84
Jamil Geor Avatar answered Sep 28 '22 02:09

Jamil Geor


You may take a look at RazorEngine.

like image 20
Darin Dimitrov Avatar answered Sep 28 '22 01:09

Darin Dimitrov