Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
bevacqua Avatar asked Feb 11 '12 19:02

bevacqua


People also ask

How do I render a Razor view to string?

Listing 1: Rendering a Razor View to String from within a Controller. 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.

How do I return a rendered Razor view from Web API controller?

ASP.NET MVC4 Web API controller should return Razor view as html in json result property. Message=The method or operation is not implemented. var viewResult = ViewEngines.

How do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.

Which is the way to render partial view using ASP.NET MVC Razor engine?

RenderPartial function to render Partial View in ASP.Net MVC Razor. The data will be fetched from database using Entity Framework and then the Partial View will be rendered using the @Html. RenderPartial function in ASP.Net MVC Razor.


2 Answers

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.

like image 163
Marc Avatar answered Oct 09 '22 01:10

Marc


You can check this link.

extracted content From Render Razor view to String. .

public static string RenderRazorViewToString(string viewName, object model) {     ViewData.Model = model;     using (var sw = new StringWriter())     {         var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);         var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);         viewResult.View.Render(viewContext, sw);         return sw.GetStringBuilder().ToString();     } } 
like image 31
Ravi Gadag Avatar answered Oct 09 '22 01:10

Ravi Gadag