How to programmatically render razor page as HTML string?

How to programmatically render razor page as HTML string?

In order to render the Page I have to manually create a ViewContext and I have to supply it with a Model. But the Page is the Model, and since it’s a Page it isn’t a simple ViewModel. It rely on DI and it expects OnGetAsync () to be executed in order to populate the Model.

How to render a partial view in ASP.NET?

To render the view use In this case your action handler will need to pass the model data to the view Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent: If your user control has it’s own data type you can also construct it within the page

How does the renderviewtostring method work in ASP.NET?

The RenderViewToString () method works by receiving a controller context and virtual view path ( i.e., ~/views/item/page.cshtml) and optional model data that are passed to the view. You can also pass a flag whether to render a partial view, which is quite common for self-contained template pages that shouldn’t render a _Layout page.

How to render a MVC view as a string?

Accepted answer from Tim Scott (changed and formatted a little by me): Assuming a call from the controller to get the order confirmation email, passing the Site.Master location. Here’s what I came up with, and it’s working for me. I added the following method (s) to my controller base class.

Is it possible to return view as string in C #?

If like me you have a number of controllers that need this, like in a reporting site, it’s not really ideal to repeat this code, and even injecting or calling another service doesn’t really seem right. So I’ve made my own version of the above with the following differences:

How to return view as string in.net core?

Create Service in file viewToString.cs as below code: 2. Add the service to the Startup.cs file, as: 3. Add “preserveCompilationContext”: true to the buildOptions in the project.json, so the file looks like: 4. Define you model, for example: 5.

How to use rendertostringasync in.net core?

The RenderToStringAsync method, used in this example, looks like this: If you implement the method as an extension method, your usage can become: I tried the solution which answered by @Hasan A Yousef in Dotnet Core 2.1, but the csthml do not work well to me.