【问题标题】:Render an ActionResult to a String, Return it as ContentResult将 ActionResult 渲染为字符串,将其作为 ContentResult 返回
【发布时间】:2013-03-15 17:01:40
【问题描述】:

我有一些代码几乎可以将 actionresult 转换为字符串。

在我执行 EditableItem 方法后,它将 html 流响应输出到 stringwriter,然后我获取 html 并对其进行修改,然后将 html 放入字符串中(带有转义字符)。

我的问题是,在代码末尾,我无法返回内容结果。我认为这是因为我弄乱了 ControllerContext。我完全确定这是否是问题所在,但这段代码为我返回了一个空白的 html 页面。但最后,readonlyHtmlString 字符串充满了很棒的 html 代码。并且呈现常规 ContentResult 也不起作用。我该如何解决这个问题?

谢谢

    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);
         localWriter.Flush();
         var htmlStringWithEscapes = localWriter.ToString();

         var htmlDoc = new HtmlDocument();
         htmlDoc.LoadHtml(htmlStringWithEscapes);

         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");

    }

【问题讨论】:

  • 我需要查看 EditableItem 操作

标签: c# asp.net-mvc-3 html-agility-pack


【解决方案1】:

我不确定为什么它不起作用,所以我放弃了代码以支持此处使用的方法...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2022-01-14
    相关资源
    最近更新 更多