Get html from MVC 4 view into a string

后端 未结 3 1400
醉酒成梦
醉酒成梦 2020-12-08 05:12

I am trying to use the accepted answer from this question.

It seems that it will be exactly what i am looking for, but i have a problem. I don\'t know how to actuall

3条回答
  •  暖寄归人
    2020-12-08 05:56

    Rather than inherit Controller which means you have to remember to implement this every time, or inherit from a CustomControllerBase, which means you have to remember to inherit every time - simply make an extension method:

    public static class ControllerExtensions
    {
        public static string RenderView(this Controller controller, string viewName, object model)
        {
            return RenderView(controller, viewName, new ViewDataDictionary(model));
        }
    
        public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData)
        {
            var controllerContext = controller.ControllerContext;
    
            var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);
    
            StringWriter stringWriter;
    
            using (stringWriter = new StringWriter())
            {
                var viewContext = new ViewContext(
                    controllerContext,
                    viewResult.View,
                    viewData,
                    controllerContext.Controller.TempData,
                    stringWriter);
    
                viewResult.View.Render(viewContext, stringWriter);
                viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
            }
    
            return stringWriter.ToString();
        }
    }
    

    Then within your Controller you can call like this:

    this.RenderView("ViewName", model);
    

提交回复
热议问题