Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Render Razor views from string

I have looked for similar questions but have not managed to build a solution yet.

Basically what I need is to render views from strings in memory.

Example:

    public IActionResult Test()
    {
        var model = new MyModel
        {
            Name = "Joe"
        };

        var cshtml = "<h1> Hello @Model.Name </h1>";

        var myView = MyAwesomeEngine.CreateView(cshtml, model);

        return View(myView)
        //or
        return myView
    }

Is this possible? I have tried RazorViewEngine inheritance without success, what would be the correct way to render views from string without looking for files in view paths?

I am using aspnetcore 1.1

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

As Legends suggested using IFileProvider method worked correctly!

Using the example of this link I was able to do it (without the database)

This was my test IFileInfo implementation:

public class MemoryFileInfo : IFileInfo
    {
        private byte[] _testContent = Encoding.ASCII.GetBytes(@"@model TestModel
            <p>@Model.Name</p>");

        private string _viewName;
        public bool Exists { get
            {
                return _viewName.Equals("/Views/Home/TestView.cshtml");
            }
        }

        public MemoryFileInfo(string name)
        {
            _viewName = name;
        }

        public long Length => _testContent.Length;

        public string PhysicalPath => null;

        public string Name => _viewName;

        public DateTimeOffset LastModified => DateTimeOffset.Now;

        public bool IsDirectory => false;

        public Stream CreateReadStream()
        {
            return new MemoryStream(_testContent);
        }
    }

This is another great solution RazorEngine but is has no support for netcoreapp1.1 yet

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!