开发者

Render view to string outside controller?

开发者 https://www.devze.com 2022-12-17 01:31 出处:网络
Is it possible to render a view from a class, which is not controller? 开发者_如何转开发 For example, I\'m having a class which will return some data, like controls, which i want to derive from my vi

Is it possible to render a view from a class, which is not controller? 开发者_如何转开发

For example, I'm having a class which will return some data, like controls, which i want to derive from my view.

Is it possible?

Thanks in advance.


The open source Razor Engine does exactly what you need: https://github.com/Antaris/RazorEngine

string razorText = System.IO.File.ReadAllText(razorTemplateFileLocation);
string emailBody = Razor.Parse(razorText, yourViewModel);


I did it using this:

Rendering ASP.NET MVC Razor Views outside of MVC

Quite easy. You just need to add one class(ViewRenderer.cs) and it is ready to use.

For example, I can put this code outside Controller:

string html = ViewRenderer.RenderView($"~/Views/Partials/Email/WelcomeEmail.cshtml", viewModel);


In a view, we have a method named Html.Partial which renders a partial to a string. Within your controller, you can instantiate an HtmlHelper instance and then call the Partial extension method on it. Make sure you import the System.Web.Mvc.Html namespace in your controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号