c# - 如何制作 Response.Write(...);在我的 Controller 中

标签 c# asp.net asp.net-mvc asp.net-mvc-3

我有一个具有以下方法的 Controller :

public void ExportList()
{
    var out = GenExport();

    CsvExport<LiveViewListe> csv = new CsvExport<LiveViewListe>(out);
    Response.Write(csv.Export());
}

这应该会生成一个用户可以下载的 csv 文件。

我在我的 View 中通过 jQuery 请求调用此方法:

$.getJSON('../Controller2/ExportList', function (data) {
    //...
});

问题是,我没有得到任何下载,我也不知道为什么。该方法被调用但没有下载。

这里有什么问题吗?

最佳答案

您的 Controller 方法需要始终返回一个 ActionResult。所以该方法应该看起来更像

public ActionResult ExportList()
{
    var export = GenExport();

    CsvExport<LiveViewListe> csv = new CsvExport<LiveViewListe>(export);
    return new CsvResult(csv);
}

其中 CsvResult 是一个继承自 ActionResult 的类,并执行必要的操作以提示用户下载您的 Csv 结果。

例如,如果您确实需要Response.Write,这可能是:

public class CsvResult : ActionResult
{
    private CsvExport<LiveViewListe> data;
    public CsvResult (CsvExport<LiveViewListe> data)
    {
        this.data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = "text/csv";
        response.AddHeader("Content-Disposition", "attachment; filename=file.csv"));

        if (data!= null)
        {
            response.Write(data.Export());
        }
    }
}

如果您的 CsvExport 类具有 Export 方法,您还可以考虑使其更通用:

public class CsvResult<T> : ActionResult
{

    private CsvExport<T> data;
    public CsvResult (CsvExport<T> data)
    {
        this.data = data;
    }

    .... same ExecuteResult code
}

现在它支持您的任何 csv 下载,而不仅仅是 LiveViewListe

关于c# - 如何制作 Response.Write(...);在我的 Controller 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784364/

相关文章:

c# - 插入带有 where 子句的语句 c#

c# - bundle 的 css 链接出现 404 错误

c# - LINQ - 加入 3 个表与分组和求和

asp.net - 从 MVC 3 迁移到 MVC 5 后,Razor 语法绑定(bind)属性不起作用

c# - 对 MVC 站点具有特定要求的粒度权限

asp.net-mvc - 使用 Html.Routelink 链接文本的 ViewBag 属性

javascript - Google oAuth - 在 JS 中验证用户,但在 C# 中使用

c# - 如何逐像素移动图像?

c# - 为什么绑定(bind) DropDownList 的功能不同于手动添加 ListItems?

c# - Web 应用程序启动时启动计时器