Render an ActionResult to a String, Return it as ContentResult c# html-agility-pack


I have some code that is almost working to convert an actionresult to a string.

After I execute the method EditableItem, it outputs the html stream response to a stringwriter, and then I get the html and modify it, and then I have the html in a string (with escape charachters).

My problem is that at the end of the code, I cant return a content result. I assume this is because I'm messing with the ControllerContext. I'm entirely sure if this is the problem, but this code returns a blank html page for me. But the end, the readonlyHtmlString string is full of great html code. And rendering a regular ContentResult doesn't work either. How can I remedy this?


    public ActionResult Readonly(long Id = 0, long id2 = 0)

         var localWriter = new StringWriter();
         var response = ControllerContext.RequestContext.HttpContext.Response;
         response.Output = localWriter;
         this.EditableItem( Id, id2 ).ExecuteResult(ControllerContext);
         var htmlStringWithEscapes = localWriter.ToString();

         var htmlDoc = new HtmlDocument();

         foreach (HtmlNode inputNode in htmlDoc.DocumentNode.SelectNodes("//input"))
            //var disabledNode = inputNode.Clone();
            inputNode.Attributes.Add("disabled", "disabled");
            //inputNode.ParentNode.ReplaceChild(inputNode, disabledNode);

         var readonlyHtmlString = htmlDoc.DocumentNode.OuterHtml;

         //should return a readonly view at this point!!
         //return Content(readonlyHtmlString, "text");

         //this code doesn't work anymore either 
         return Content(String.Format("This is the Material Item Controller > Readonly and Id is {0} and id2 is {1}",Id, id2),"text");

3/15/2013 5:01:40 PM

Popular Answer

I'm not sure why it wasn't working, so I scrapped the code in favor of the methods used here...

Render an MVC3 action to a string from a WCF REST service method

5/23/2017 11:50:09 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow