Render partial view to string MVC4
Asked Answered
S

2

7

I am using the following to render a partial view to a string...

        protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            ViewEngineResult 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();
        }
    }

However it returns the html with strange tags like this below... (I have included a small section as its a big view)

<$A$><div</$A$><$B$> class="modal hide fade"</$B$><$C$> id="dialog"</$C$><$D$> 

This happens throughout the HTML. This section should look like this...

<div class="modal hide fade" id="dialog" style="display: none;">
Slashing answered 2/10, 2013 at 17:1 Comment(1)
possible duplicate of MVC4 - how to render a view a string?Evansville
S
1

Strange, after a Clean and Rebuild it fixed the issue, must be a VS gremlin.

Slashing answered 4/10, 2013 at 8:17 Comment(0)
D
11

The following code has always worked for me. Though I can't see any major differences, and can't understand fully why you'd get the output you're getting.

public static String RenderRazorViewToString(ControllerContext controllerContext, String viewName, Object model)
        {
        controllerContext.Controller.ViewData.Model = model;

        using (var sw = new StringWriter())
            {
            var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
            var ViewContext = new ViewContext(controllerContext, ViewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
            ViewResult.View.Render(ViewContext, sw);
            ViewResult.ViewEngine.ReleaseView(controllerContext, ViewResult.View);
            return sw.GetStringBuilder().ToString();
            }
        }
Desmoid answered 3/10, 2013 at 23:55 Comment(1)
Hi Tentux, thank you for your answer, after a Clean and Rebuild it fixed the issue, must be a VS gremlin.Slashing
S
1

Strange, after a Clean and Rebuild it fixed the issue, must be a VS gremlin.

Slashing answered 4/10, 2013 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.