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.

1
  • 1
    Have you tried something? Can you share a little bit more of your investigations/code? Commented Dec 6, 2018 at 17:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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!
Take a look at his blog post. There is a section called Rendering without a ControllerContext, although it doesn't look easy.
@Vik78 so you want a web server but without the web server?
@Vik78 Look up the razor templating engine. It can be used outside ASP.Net.
I'm currently looking into this open-source Razor engine mentioned in the blog post: github.com/Antaris/RazorEngine So far it seems to work well. Thanks for the tips!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.