rendering view as a string

I can’t remember who the original writer of this code was, so forgive me for plagiarizing. As part of a project I’m involved in (see previous post), I needed to output a rendered html partial view so as to append to a div element. Here’s the code that helped me achieve this.

protected string RenderPartialViewToString(string viewName, object model)
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
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();

view raw
hosted with ❤ by GitHub

I hope it helps.

rendering view as a string

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s