Razor Engine for Parsing Razor Pages Stored as String

In the previous blog, I covered how MVC Razor engine can be used separately to parse the razor view stored outside the application. This blog covers the case when View is not stored as cshtml page but is stored simply as text in Database or somewhere else. Only additional step, we have to add is to create a virtual view through VirtualPathProvider.

To demonstrate the real usage of this scenario, I have created a sample application which sends the email where the email template is stored as Razor View in Resource File. Similarly, the template can also be stored in Database. Razor View stored as string in Resource file is shown below.

<div> Dear @Model.Name,</div>


  Total Marks attended by you in Exam is <span style="color:green"> @Model.Marks</span> out of 100



Your Rank is <span style="color:green"> @Model.Rank</span>

@if (@Model.Rank == 1)
    <h2>Congrats, Please collect your Gold Medal from the Director's office</h2>
else if (@Model.Rank > 30)
    <h2 style="color:red">Please collect your transfer certificate from Director's Office after clearing all your Dues</h2>

This page uses Model of type Student which is defined as

 public class Student
        public int Id { get; set; }

        public string Name { get; set; }

        public int Marks { get; set; }

        public int Rank { get; set; }

        public string EmailId { get; set; }

Stored View will use this Student model to render the HTML response.

I created a page for sending mail and previewing email which will use above Razor template.

created a page for sending mail

This page has two buttons for sending and previewing the email. Below actions will be called when clicking the “Preview Emails” and “Send Emails” buttons.

        public ActionResult PreviewEmail(int studentId)
            string emailHTML = CreateEmail(studentId);
            return Json(new { HTML = emailHTML }, JsonRequestBehavior.AllowGet);  


        public ActionResult SendMail(int studentId)

            EmailService services = new EmailService();
            Email emailEntity = new Email();
            emailEntity.Subject = "Your Result Announced!";
            emailEntity.Content = CreateEmail(studentId);
            if (services.SendEmail(emailEntity))
                return Json("Success");
            return Json("Failure");


For demonstration purpose, i will use only the preview feature of application.On clicking this button, PreviewEmail action will be called. You can notice the CreateEmail Method being called within the action. This Method is doing the main task of invoking the method for rendering the HTML from stored Razor view.

  private string CreateEmail(int studentId)
            Student student = GetStudentById(studentId);

            //Create temporary view file
            string guid = Guid.NewGuid().ToString();
            string tempFilePath = "/Views" + "/Temp/" + guid + ".cshtml"; 
            // Delete temporary file after usage
            RazorViewGenerator helper = new RazorViewGenerator();
            string emailTemplate = EmailResources.EmailTemplate; // Read from Resource File or DB
            string emailHTML = helper.Parse(student, ControllerContext, tempFilePath, emailTemplate);
            return emailHTML;

        private Student GetStudentById(int id)
            Student student = new Student(); // All hard coded to demonstrate, in actual it may fetch from DB
            student.Id = id;
            student.Name = "Alice";
            student.Rank = 1;
            student.Marks = 78;
            student.EmailId = "alice@bob.com";
            return student;


Currently, Student information is hardcoded to create the model but it will normally be fetched from database. This Student model is being passed along with the temporary file path to the Parse method of RazorViewGenerator class.

The exact implementation of Parse with RazorViewGenerator class is shown below. This method generates the actual HTML string from Razor

        public static Dictionary<string, string> pathMapDictionary = new Dictionary<string, string>();

        public string Parse(object ViewModel, ControllerContext controller,string tempFilePath,string template)

                var sb = new StringWriter();
                ViewDataDictionary viewData = new ViewDataDictionary();
                pathMapDictionary.Add(tempFilePath, template); // Add template to dictionary which virtual path provider will access
                var tempData = new TempDataDictionary();
                viewData.Model = ViewModel;
                var razor = new RazorView(controller, tempFilePath, null, false, null);
                var viewContext = new ViewContext(controller, razor, viewData, tempData, sb);
                razor.Render(viewContext, sb);
                return sb.ToString();

            catch (Exception exx)

The static variable pathMapDictionary,having path variable as key stores the string from resource file . Our VirtualPathProvider gets the path and access this dictionary to get corresponding template string. In the parse method you can see that the path of cshtml file is just a non-existing file path. In the previous Blog, there was real cshtml file at this location.

Now the main trick is done by the VirtualRazorPathProvider class implementing methods of VirtualPathProvider. It contains logic that whenever the file is tried being read at the “/Views/Temp” directory, it returns the required string just like original file would have returned. This is being done by GetFile and Open method respectively, as shown in the code below.

public class VirtualRazorPathProvider : VirtualPathProvider

        public VirtualRazorPathProvider()
            : base()

        public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart)
            return null;

        public override bool FileExists(string virtualPath)
            if (virtualPath.StartsWith("/Views/Temp") || virtualPath.StartsWith("~/Views/Temp"))
                return true;

            return base.FileExists(virtualPath);

        public override VirtualFile GetFile(string virtualPath)
            if (virtualPath.StartsWith("/Views/Temp") || virtualPath.StartsWith("~/Views/Temp"))
                return new StringFile(virtualPath);

            return base.GetFile(virtualPath);

        public class StringFile : System.Web.Hosting.VirtualFile
            string path; // Path is the Key of Dictionary and is Associated value is Razor Template
            public StringFile(string path)
                : base(path)
                this.path = path;

            public override System.IO.Stream Open()

                var stream = new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(RazorViewGenerator.pathMapDictionary[path]));
                // RazorViewGenerator.pathMapDictionary[path] returns email Template
                return stream;




The VirtualRazorPathProvider class needs to be registered at Application_Start event of Global.asax file.

protected void Application_Start()


            System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(new VirtualRazorPathProvider());

The generated HTML is shown on the screen as shown below.You can create your own template and design as per your need.


Concluding Points

We can have multiple different razor templates stored as a entry in Database or resource file. Consider a scenario where the different department has different design for the email template.Corresponding views can be used for sending email for each department.Also, The Email template can be managed directly by department avoiding need of giving access to complete application.Thus,it makes views loosely coupled from application.A little extra separation of View than MVC was intended for!

You might also like