Skip to main content
 首页 » 编程设计

c#之asp.net 上的按钮单击创建 CSV 文件,下载它并刷新页面

2024年02月13日18mfrbuaa

是否无法从页面(和数据库)收集信息、根据给定信息创建 csv 文件、下载创建的文件和刷新页面?

当前用户看到一个包含行的表格,通过选中复选框选择行,按“导出”按钮,CSV 文件将创建并下载到用户计算机。问题出在页面刷新上。

目前在按钮上点击 CSV 是通过以下方式创建和下载的:

        //here is create csv function and then the result is outputed 
        Response.Clear() 
        Response.Buffer = True 
        Response.AddHeader("content-disposition", "attachment;filename=DataTable.csv")         
        Response.Charset = "" 
        Response.ContentType = "application/text" 
 
        Response.Output.Write(CsvFile.ToString(), 0) 
        Response.Flush() 
        Response.End() 

下载 csv 文件后,此解决方案会导致页面刷新出现问题。

1) 此链接: Redirecting to another page after Response.End() has been called in C#

建议 `Response.AddHeader("Refresh", "3; url=index.html");那应该刷新页面。 这不起作用,没有重定向发生。

2) 建议的另一种解决方案是创建一些额外的 URL 并允许用户从给定的 URL 下载文件。这不符合我的情况,因为文件是根据页面上的数据创建的。

3) 是否有任何其他解决方案满足需求(按钮点击创建 csv 并下载它,页面被刷新)?

你能给我一些线索吗?

请您参考如下方法:

您将需要在客户端上使用一些 javascript 以获得您想要的结果。我从这里学习了基础知识 https://stackoverflow.com/a/4168965/1002621这是一个带有 php 后端的示例。

您在客户端上需要的代码看起来像这样 基本前提是您使用 jquery 拦截您的下载按钮单击事件,以便可以将 token 注入(inject)到表单发布中,然后您可以在响应中发回知道文件下载已完成,然后执行您自己的表单提交/其他操作。

<script type="text/javascript"> 
 
    function DownloadAndRefresh() { 
 
        //get form and inject a hidden token input 
        var form = $(this).closest('form'); 
        var tokenInput = $('input[name=token]'); 
        if (tokenInput.length == 0) { 
            tokenInput = $('<input />').prop('type', 'hidden').prop('name', 'token'); 
            form.append(tokenInput); 
        } 
 
        //create a unqiue token we can watch for and set the hidden inputs value 
        var token = new Date().getTime(); 
        tokenInput.prop('value', token); 
 
        //watch for the token to come back in the documents cookie (this is set on server) 
        var tokenInterval = setInterval(function () { 
            //check to see if the cookie contains the token yet 
            if (document.cookie.indexOf(token) != -1) { 
                //submit the form again now the file has been downloaded (this causes a standard postback) 
                form[0].submit(); 
                window.clearInterval(tokenInterval); 
            } 
        }, 200); 
 
        //wait up to 60 seconds for the token then stop the interval because something probably went wrong 
        setTimeout(function () { window.clearInterval(tokenInterval); }, 60000); 
 
        //allow the current post action to continue 
        return true; 
 
    } 
 
    $(document).ready(function () { 
        //call the DownloadAndRefresh function before posting to the server 
        $('#<%= DownloadButton.ClientID %>').on('click', DownloadAndRefresh); 
    }); 
 
</script> 
 
<asp:Button runat="server" ID="DownloadButton" Text="Download Button" onclick="Download_Click" />  

服务器代码非常简单,只需要从请求表单中提取 token 并将其放入响应 cookie 中即可。

    protected void Download_Click(object sender, EventArgs e) 
    { 
        Response.Clear(); 
 
        //set the response token cookie to be the token sent in the form request 
        Response.SetCookie(new HttpCookie("token", Request.Form["token"])); 
        Response.Buffer = true; 
        Response.AddHeader("content-disposition", "attachment;filename=file.txt"); 
        Response.ContentType = "text/plain"; 
        Response.Output.Write("some text"); 
        Response.End(); 
    }