Skip to content

Instantly share code, notes, and snippets.

@nsbingham
Forked from cassioeskelsen/RenderViewToString.cs
Created January 7, 2013 01:57
Show Gist options
  • Save nsbingham/4471686 to your computer and use it in GitHub Desktop.
Save nsbingham/4471686 to your computer and use it in GitHub Desktop.
/*
* Original Sample: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
*/
public class HomeController : Controller
{
public ActionResult Index()
{
string MyModelData = "";
var teste = RenderPartialViewToString("About", MyModelData);
return View();
}
public ActionResult About()
{
return View();
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment