将数据写入Response,但保持页面处于活动状态

时间:2014-04-15 13:43:47

标签: c# asp.net sharepoint-2010 httpresponse response.write

我试图让用户点击网页上的按钮下载CSV文件,但是我在向用户发送正确的数据时遇到了问题。此外,一旦文件被下载,我希望页面保持"活动"即页面可以继续向服务器触发事件​​,例如再次单击“下载”按钮。

这是我目前使用的代码,拼凑在各种SO问题中:

var sb = new StringBuilder();
string fileName = "data.csv";
// Build CSV file...
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("filename={0}", fileName));
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

这可以为用户提供打开或下载文件的选项,但该文件还包含所请求数据后的aspx文件的整个标记,并且页面完全处于非活动状态。

我猜测问题出在上面代码的最后两行。我尝试过使用ApplicationInstance.CompleteRequest代替Response.End,但这似乎并没有改变结果。页面仍处于非活动状态,文件末尾仍有标记。有人可以帮忙吗?

如果Response的行为有任何不同,则该页面在SharePoint 2010中为WebPartPage

2 个答案:

答案 0 :(得分:1)

试试这个

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); HttpContext.Current.Response.ContentType = "application/CSV";

答案 1 :(得分:1)

设置行

HttpContext.Current.Response.AddHeader("content-disposition", "filename={0}", fileName));

HttpContext.Current.Response.AppendHeader("content-disposition", String.Format("attachment;filename={0}", fileName));

并在按钮上设置以下属性

downloadButton.OnClientClick = "_spFormOnSubmitCalled = false;";

_spFormOnSubmitCalled是Sha​​rePoint用于停止多个表单提交的javascript变量,单击下载按钮时将其设置为true。

相关问题