How to Render a Razor View to a String in ASP.NET MVC 3

How to render an ASP.NET MVC view as a string?

Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)

MVC2 .ascx style

protected string RenderViewToString<T>(string viewPath, T model) {
ViewData.Model = model;
using (var writer = new StringWriter()) {
var view = new WebFormView(ControllerContext, viewPath);
var vdd = new ViewDataDictionary<T>(model);
var viewCxt = new ViewContext(ControllerContext, view, vdd,
new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}

Razor .cshtml style

public 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);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}

Edit: added Razor code.

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

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.

Render Razor View to string?

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

How to display html action as string in mvc 3 razor view

This works for me, just tried in a local MVC project:

@{
string test;
test = @Url.Action("actionName");
}

Render Razor View to string in ASP.NET Core

UPDATE July, 2016

Working fine on the following versions 1.0.0, RC2


Who's targeting aspnetcore RC2, this snippet might help you:

  • Create a separate Service, so you can use it either if you are not in a controller context, e.g. from a command line or on a queue runner, etc ...
  • Register this service in your IoC container in the Startup class

https://gist.github.com/ahmad-moussawi/1643d703c11699a6a4046e57247b4d09

Usage

// using a Model
string html = view.Render("Emails/Test", new Product("Apple"));

// using a Dictionary<string, object>
var viewData = new Dictionary<string, object>();
viewData["Name"] = "123456";

string html = view.Render("Emails/Test", viewData);

Notes

Links in Razor are rendered as relative URL, so this will not work on external views (like emails, etc ...).

As for now am generating the link on the controller and pass it to the view through the ViewModel.

Credit

The source is extracted from (Thanks To @pholly): https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.RenderViewToString/RazorViewToStringRenderer.cs)

Render razor view to string without munging the html

This is actually a bug I ran into during the summer, see bug report and response from Microsoft here bug and workaround. Good news is that according to MS it should be fixed when VS2013 is released.

Workaround is to disable the browser link feature see here browser link feature

ASP.NET CORE Render Razor View to string with controller parameters

I think you may understand the usage of RenderRazorViewToString.This method is called by the following code:

Helper.RenderRazorViewToString(controller, "PartialViewName", model);

The second parameter is not the method name,it is the partial view name.It would not get to the IndexPartial method.

What you want is to parse the partial view with model to string.The model data get by manipulating query by searchValue and filterValue.

To meet your requirement,what you need do should be like below:

public string IndexPartial(string? searchValue, string? filterValue)
{
var model = _context.Pupils
.Where(a => a.Name.Contains(searchValue)&& a.Email.Contains(filterValue))
.FirstOrDefault(); //Manipulate query by searchValue and filterValue

//pass the correct model to the RenderRazorViewToString method
//then it would render the partial view to the correct string
var data = Helper.RenderRazorViewToString(this, "PartialViewName", model);
return data;
}

Result:
Sample Image



Related Topics



Leave a reply



Submit