0

I want to let user download data I am displaying elsewhere in the website as reports.

I am using Asp.net core 2.1 rc1 MVC app.

My cunning plan was to create a special view which would render data as a tab delimited text and use response headers to make browser download it instead of displaying HTML. This almost works perfectly.

My "HttpGet" code in the controller looks like this:

 Response.Headers.Add("Content-disposition", "attachment; filename=export.tsv");
 return View(MyModel);

My razor view looks like this:

@Model IEnumerable<MyModel>
@{
     Layout = null;
     String LineBreak = Environment.NewLine;
     String Tab = "\t";
}

Header1 Header2 ...

    @if (Model.Count > 0)
    {
        foreach (MyModel myModel in Model)
        {
            @myModel.Field1@Html.Raw(@Tab)@myModel.Field2 ... @Html.Raw(@LineBreak)
        }
    }

This works splendidly except that this ugly error message appears as a first line in the file:

System.Collections.Generic.List`1[MyApp.Models.MyModel] IEnumerable<MyModel>

The rest of the file is exactly what I need.

Does anyone know how to remove this message? Or if there is something wrong with my general approach...

Full project available here: https://github.com/under3415/ExportError/ (just click on download link and examine the file)

under
  • 2,519
  • 1
  • 21
  • 40

2 Answers2

1

You've written @Model, while the correct syntax is @model (lowercase - it's case-sensitive).

A first-line @model directive specifies the model type. @Model dereferences the actual model instance. What you're seeing is its ToString representation.

khellang
  • 17,550
  • 6
  • 64
  • 84
0

You're getting this error because you're returning view with the model return View(MyModel);, you should be using FileResult

Here are the complete instructions on it Download file of any type in Asp.Net MVC using FileResult?

Ikram Shah
  • 1,206
  • 1
  • 11
  • 12
  • I don't really want to return a file. All my formatting is done in the view. I can easily return an Excel file or a tab delimited text file. I want to return a view and have browser save it as a file. If I was going to use a file instead of file, I guess I would have to create the file in memory and stream it to a file. This is so much easier done in a view. – under May 14 '18 at 08:51