How to get view html and return to client side

后端 未结 3 960
太阳男子
太阳男子 2021-01-06 08:19

below is code snippet which return view to jquery function but i like to know how could i extract or get the view html and return to client end.

$(function(         


        
3条回答
  •  萌比男神i
    2021-01-06 08:29

    You can use this method , passing the ActionResult from controller and getting back html from the view

        private string RenderActionResultToString(ActionResult result)
        {
            // Create memory writer.
            var sb = new StringBuilder();
            var memWriter = new StringWriter(sb);
    
            // Create fake http context to render the view.
            var fakeResponse = new HttpResponse(memWriter);
            var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request,
                fakeResponse);
            var fakeControllerContext = new ControllerContext(
                new HttpContextWrapper(fakeContext),
                this.ControllerContext.RouteData,
                this.ControllerContext.Controller);
            var oldContext = System.Web.HttpContext.Current;
            System.Web.HttpContext.Current = fakeContext;
    
            // Render the view.
            result.ExecuteResult(fakeControllerContext);
    
            // Restore old context.
            System.Web.HttpContext.Current = oldContext;
    
            // Flush memory and return output.
            memWriter.Flush();
            return sb.ToString();
        }
    

提交回复
热议问题