c# - 自定义 View 引擎与自定义操作结果

标签 c# asp.net-mvc csv viewengine actionresult

我有一个场景,用户可以选择单击“下载”按钮,我应该创建一个包含历史数据的 csv 文件,然后让用户在本地保存该文件。由于我以前没有这样做过,所以我开始寻找如何执行此操作,并且基本上遇到了自定义 View 引擎和自定义操作结果。

我现在的问题是这些有什么好处/坏处?首选的方法是什么?

CSV 文件基本上只包含标题和数千行数据(最多约 15 列/字段)。所以真的没什么特别的。

最佳答案

我可能会选择自定义操作结果(我的示例中的实际序列化是通过 FileHelpers 完成的):

public class CsvResult<T> : ActionResult
{
    public IEnumerable<T> Records { get; private set; }
    public CsvResult(IEnumerable<T> records)
    {
        Records = records;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "text/csv";
        var engine = new FileHelperEngine(typeof(T));
        engine.WriteStream(response.Output, Records);
    }
}

[DelimitedRecord(",")] 
public class Customer 
{
    public int Id { get; set; }
    public string Name { get; set; }         
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var customers = new[]
        {
            new Customer { Id = 1, Name = "customer 1" },
            new Customer { Id = 2, Name = "customer 2" },
        };
        return new CsvResult<Customer>(customers);
    }
}

您甚至可以通过使用扩展方法来美化此返回语句(在这种情况下,泛型是丑陋且多余的):

public static class ControllerExtensions
{
    public static ActionResult Csv<T>(this Controller controller, IEnumerable<T> records)
    {
        return new CsvResult<T>(records);
    }
}

然后简单地:

public ActionResult Index()
{
    var customers = new[]
    {
        new Customer { Id = 1, Name = "customer 1" },
        new Customer { Id = 2, Name = "customer 2" },
    };
    return this.Csv(customers);
}

关于c# - 自定义 View 引擎与自定义操作结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3310698/

相关文章:

c# - 派生类的 XML 序列化

c# - 是否有可以与传入的 KeyEventArgs 匹配的热键的 .NET 类?

c# - 多个线程使用的 Post Sharp 属性中的唯一记录器

css - 如何将 Devexpress 主题应用到基本的 html 表格?

c# - 如何在代码片段中放置空文字

c# - HttpContext.Current.Cache 与 HttpRuntime.Cache

c# - 使用 Bootstrap Datepicker 选择 future 日期并将其传递给 ASP.NET MVC Controller

python - 只有 unicode 字符串的第一个字符被写入 csv

java - 如何使用 Java 在 SPARK 中使用映射函数

php - 抓取完整网站以获取特定 div 标签内的数据,其中 url 包含字符串