Render View for a string

Asked

Viewed 119 times

0

I took a code right here in the stack to render a view to string.

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

Does anyone have any idea how to render a view that is in 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();
        }
    }

2 answers

0

this code falls into the same problem I had..

I made some changes and managed to at least call the View, but now the problem is being when passing a Viewbag to the View...

Can anyone tell me why?

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

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.