Mvc渲染动作/部分响应输出

时间:2015-12-30 22:09:52

标签: asp.net-mvc html.renderpartial

虽然@Html.RenderPartial调用了write并返回void,但它仍在写入StringWriter / StringBuilder。有没有办法直接呈现ResponseStream

是否可以使用自定义IViewEngine来实现PdfView之类的渲染,直接输出到ResponseStream

ADDITION

ViewResultBase.ExecuteResult显示使用ViewContext构建的Response.Output,但调试器将ViewContext.Writer显示为StringWriter

这两种方法都会产生StringWriter

return PartialView("view", Model)
// or
PartialView("view", Model).ExecuteResult(ControllerContext)

修改

似乎System.Web.WebPages.WebPageBase ExecutePageHeirarchy将临时StringWriter推送到上下文堆栈,所以我不确定是否可以绕过它

摘要

RenderPartial,RenderAction不直接输出到Response.Stream,Razor Views都不会

新的WebPages / Razor渲染引擎使用StringWriter将所有内容包装到StringBuilder。解决方案是更改我的页面以使用不适用此包装的WebFormViewEngine

1 个答案:

答案 0 :(得分:0)

以下方法说明了实现您正在寻找的结果的一种方法:

// <summary>
// An extension methods for rendering a model/view into a stream
// </summary>
// <param name="myModel">The model you are trying render to a stream</param>
// <param name="controllerBase">This will come from your executing action</param>
// <returns></returns>
        public static Stream GetStream(CustomModel myModel, ControllerBase controllerBase)
        {
            //we will return this stream
            MemoryStream stream = new MemoryStream();

            //you can add variables to the view data
            controllerBase.ViewData["ViewDataVariable1"] = true;

            //set your model
            controllerBase.ViewData.Model = myModel;

            //The example uses the UTF-8 encoding, you should change that if you are using some other encoding.
            //write to a stream
            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
            {
                using (var sw = new StringWriter())
                {
                    //render the view  ~/Views/Shared/_FeedbackMessage.cshtml (can be passed in as a parameter if you want to make it super generic)
                    var viewResult = ViewEngines.Engines.FindPartialView(controllerBase.ControllerContext, "_FeedbackMessage");

                    //create a new view context
                    var viewContext = new ViewContext(controllerBase.ControllerContext, viewResult.View, controllerBase.ViewData, controllerBase.TempData, sw);

                    //Render the viewengine and let razor do its magic
                    viewResult.View.Render(viewContext, sw);    
                    viewResult.ViewEngine.ReleaseView(controllerBase.ControllerContext, viewResult.View);

                    //get StringBuilder from StringWriter sw and write into the stream writer
                    //you could simply return the StringWriter here if that is what you were interested in doing
                    writer.Write(sw.GetStringBuilder().ToString());

                    writer.Flush();

                    stream.Position = 0;
                }

            }

            //return the stream from the above process
            return stream;
        }