我不完全确定如何,但似乎页面生命周期在 .NET 2.0 和 .NET 4.0 之间略有变化。我能够复制这个问题。
我假设您的视图看起来像这样:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MyMaster" Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
<asp:Content Id="MainContent1" ContentPlaceHolderID="MainContent">
<%
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.Write(Html.CompletionByTemplateExport((CompletionByTemplateExport)ViewData["report"]));
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=CompletionByTemplateReport.csv");
context.Response.End();
%>
</asp:Content>
不幸的是,我相信你必须做这样的事情:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MyMaster" Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
<script runat="server">
void Page_Load(object sender, EventArgs args) {
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.Write(Html.CompletionByTemplateExport((CompletionByTemplateExport)ViewData["report"]));
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=CompletionByTemplateReport.csv");
context.Response.End();
}
</script>
或者(更好),将该代码移动到控制器中(因为这是 MVC):
public class MyController : Controller
{
public ActionResult Index()
{
// This is redundant, Controllers and Views have a Response property
// HttpContext context = HttpContext.Current;
CompletionByTemplateExport reportData = ...;
Response.Clear();
Response.Write(Html.CompletionByTemplateExport(reportData));
Response.ContentType = "text/csv";
Response.AppendHeader("Content-Disposition", "attachment; filename=CompletionByTemplateReport.csv");
Response.End();
}
}
其中任何一个都会为您提供没有母版页 HTML 的 CSV。