虽然@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
。
答案 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;
}