Render View to a string

0

I've got a code right here on the stack to render a view to string.

When the view to be converted is in the same context ie in the same folder of the controller it works normally, but if I try to render a view that is in another controller does not work.

Does anyone have any idea how I can render a view that is on another Controller?

    public string RenderRazorViewToString(string viewName, object model)
    {
        //aqui mudei o codigo para tentar chamar um Controller fora do contexto atual, mas não rolou
        Controller controller = new PedidoController();

        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
    
asked by anonymous 12.07.2015 / 20:34

2 answers

0

> help you? I hope this link can clarify something. The only thing is that it is in English.

    
13.07.2015 / 01:50
0

This code falls on the same problem I had ..

I have made some changes and managed to at least call View, but now the problem is when I pass a ViewBag to the View ...

Can anyone tell me why?

Follow changed method.

        public string RenderRazorViewToString(string viewName, object model)
    {
        Controller controller = new PedidoCompraController();
        var wrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
        var routeData = new System.Web.Routing.RouteData();

        if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller"))
            routeData.Values.Add("controller", controller.GetType().Name
                                                        .ToLower()
                                                        .Replace("controller", ""));

        controller.ControllerContext = new System.Web.Mvc.ControllerContext(wrapper, routeData, controller);

        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
    
13.07.2015 / 04:13