1

Possible Duplicate:
How to Render Partial View into a String

I am looking to render a Partial in my C# code to string, does anyone know how I can achieve this? The partial is just a good old partial that sits in the Partials directory and will not be used by anything else.

Community
  • 1
  • 1
Funky
  • 12,890
  • 35
  • 106
  • 161
  • Check this question http://stackoverflow.com/questions/2537741/how-to-render-partial-view-into-a-string – 22db05 Aug 14 '12 at 09:12

2 Answers2

1
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();
    }
}

Also refer: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

Chaim Zonnenberg
  • 1,793
  • 13
  • 10
0

You can Use HTML.Partial which returns an MvcHtmlString, now on that you can use a ToString() method and so you get a string. Do not confuse with HTML.RenderPartial();

Html.Partial or Html.RenderPartial with MVC3?

Community
  • 1
  • 1
Freeman
  • 5,691
  • 3
  • 29
  • 41