Search code examples
asp.net-mvcasp.net-mvc-4asp.net-mvc-partialviewviewenginestringwriter

Render partial view to string MVC4


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;">

Solution

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