如何做出Response.Write(...);在我的控制器中 [英] How to make a Response.Write(...); in my Controller

查看:67
本文介绍了如何做出Response.Write(...);在我的控制器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用以下方法的控制器:

I have a Controller with the following method:

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

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

这应生成一个供用户下载的csv文件.

this should generate a csv file which the user can download.

我在自己的视图中通过jQuery请求调用此方法:

I call this method via a jQuery request in my view:

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

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

the problem is, that I don't get any download and I don't know why. The method is called but without a download.

这是怎么了?

推荐答案

您的控制器方法需要始终返回 ActionResult .因此该方法应该更像

Your controller methods need to always return an ActionResult. So the method should look more like

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

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

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

Where CsvResult is a class inheriting from ActionResult and doing the necessary to prompt the user for download of your Csv results.

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

For example, if you really need to Response.Write this could be:

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 方法,您也可以考虑使其更通用:

You could also think about making this more generic, if your CsvExport class has the Export method:

public class CsvResult<T> : ActionResult
{

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

    .... same ExecuteResult code
}

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

Now it supports any of your csv downloads, not just LiveViewListe.

这篇关于如何做出Response.Write(...);在我的控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆