Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c# - How to render a Razor View to a string in ASP.NET MVC 3?

I've been searching the site a lot, but all I could find were examples on how to render partial controls .ascx, or depended on a controller context.

I want a method that enables me to provide just the relative path to the view, and a model, and render that view with that model into a string:

string result = Utility.RenderViewToString("~/Views/My/Profile.cshtml", model);

All the examples I could find were either for older versions of MVC, or simply didn't do what I need to do here.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can achieve that with the razorengine.

string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

And it does not rely on the controller context - but because of that you are not able to use the Html helpers (which rely on the http context). But it is perfect to use razor as a template engine for strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...