我有一个方法
RenderToString(string pathToView, string pathToMasterPage)
,与已经说过的名称一样,呈现视图并将结果作为字符串返回。目前,我必须将路径作为方法的参数传递给母版页。但由于视图本身已经包含母版页的定义
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
我想知道是否可以以编程方式读取此值,以便我不必再将其作为单独的参数传递?
答案 0 :(得分:1)
RenderToString方法如下所示:
public virtual string RenderToString(string viewPath, string masterPath)
{
ControllerContext controllerContext = this.ControllerContext;
Stream filter = null;
ViewPage viewPage = new ViewPage();
viewPage.ViewContext = new ViewContext(this.ControllerContext, new WebFormView(viewPath, masterPath), this.ViewData, this.TempData);
//get the response context, flush it and get the response filter.
var response = viewPage.ViewContext.HttpContext.Response;
response.Flush();
var oldFilter = response.Filter;
try
{
//put a new filter into the response
filter = new MemoryStream();
response.Filter = filter;
//render the view into the memorystream and flush the response
viewPage.ViewContext.View.Render(viewPage.ViewContext, viewPage.ViewContext.HttpContext.Response.Output);
response.Flush();
//read the rendered view
filter.Position = 0;
var reader = new StreamReader(filter, response.ContentEncoding);
return reader.ReadToEnd();
}
finally
{
//Clean up.
if (filter != null)
{
filter.Dispose();
}
//Now replace the response filter
response.Filter = oldFilter;
}
}
这不完美。执行该方法后,您无法再执行任何重定向,因为必须刷新响应,因此已经发送了标头。如果您找到了解决方法,请在此处发布。