Render partial view to string MVC4

♀尐吖头ヾ 提交于 2019-11-30 14:29:33

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!