0

I'm wondering whether there's a way that I can instantiate an object or call a utility function that will simply take in an object and perhaps a path to a view as parameters, and return a string that consists of the rendered view, using the object as the model.

I don't want to go through the usual ASP.NET request pipeline, or deal with dependency injection or even depend on the framework running to provide a bunch of services.

I simply want an easy way to render a view to a string in code.

Does this exist?

If anyone knows of any good sources on how view rendering in ASP.NET works under the hood, that would also be very helpful.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Vik78
  • 305
  • 1
  • 2
  • 14

1 Answers1

2

Yes. I did this in one of my projects. I stole the ViewRenderer class from here: https://github.com/RickStrahl/WestwindToolkit/blob/master/Westwind.Web.Mvc/Utils/ViewRenderer.cs

You can either install the Westwind.Web.Mvc NuGet package, or just do as I did and just copy the class to your project.

You use it like this:

var r = new ViewRenderer();
var viewAsString = r.RenderViewToString("~/Views/MyView.cshtml");

You can optionally pass a second parameter with the model.

Here is the author's blog post describing how it works: https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • Thanks, this is definitely the most helpful thing I've seen so far. However, it looks like you still need a ControllerContext or HttpContext.Current to be set to make this work, which means unfortunately (to my understanding) that you are still dependent on the framework to provide those things for you. I'm trying to render the view to a string in normal code, without even having to run an ASP.NET web server in the background. This does look promising though, and I'll look at it closely. Thanks! – Vik78 Dec 06 '18 at 18:14
  • Take a look at his blog post. There is a section called [Rendering without a ControllerContext](https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String#Rendering-without-a-ControllerContext), although it doesn't look easy. – Gabriel Luci Dec 06 '18 at 18:21
  • @Vik78 so you want a web server but without the web server? – No Refunds No Returns Dec 06 '18 at 19:22
  • @Vik78 Look up the razor templating engine. It can be used outside ASP.Net. –  Dec 06 '18 at 19:26
  • I'm currently looking into this open-source Razor engine mentioned in the blog post: https://github.com/Antaris/RazorEngine So far it seems to work well. Thanks for the tips! – Vik78 Dec 06 '18 at 19:42