0

I need to render my razor view to string. I would like to pass my model:

public class ContactDetails
{
    public string Name { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
}

and use it in my razor view and then render it to the string.

I heard about RazorEngine but I would like to do it without it. Also I don't have an controller context.

Maybe I need fake some controller context?

Is it possible to do it? Do you have any idea how can to solve this problem?

mskuratowski
  • 4,014
  • 15
  • 58
  • 109
  • 2
    Why must do that? – Tân Jan 18 '17 at 17:44
  • It is not duplicate because I don't want to use controller context – mskuratowski Jan 18 '17 at 17:48
  • 2
    I think you mean 'render' not 'parse'. Why do you want to avoid `RazorEngine`? It's a lot of code to rewrite and this isn't the place to ask for a rewrite of it from scratch! As an alternative, you can do an HTTP request back to your own site and render the page that way. – Ian Mercer Jan 18 '17 at 18:11
  • 1
    I'm trying to figure out if you're doing something that is going to make your life harder for no reason. – KSib Jan 18 '17 at 18:19
  • That's right I ment render. So do you have any resources where I can find some tips how to do it? I would like to write by myself without RazorEngine – mskuratowski Jan 18 '17 at 18:20
  • 1
    Possible duplicate of [Render a view as a string](http://stackoverflow.com/q/483091/11683), but you must have a controller context. How can you run anything in ASP.NET MVC without one? – GSerg Jan 18 '17 at 18:41
  • @GSberg I would like to use it in my service class, so how can I prepare my controller context ? – mskuratowski Jan 18 '17 at 18:49
  • 1
    Your call begins in a controller where you have controller context. Pass it to where you need to render the view as a parameter. – GSerg Jan 18 '17 at 19:18

2 Answers2

2

You may want to check out https://github.com/RickStrahl/Westwind.RazorHosting - it shows how to render strings using the razor engine without a controller

Rick Hodder
  • 2,189
  • 3
  • 26
  • 54
0

There's a much simpler library called Razor.Templating.Core which works in both MVC and out of MVC Context. Supports .NET Core 3.1 and above versions.

Soundar Anbu
  • 129
  • 5