Jedi Master Spooky
Jedi Master Spooky

Reputation: 5809

How to Generate a Link to download a File in asp.net MVC?

I am testing Doddle Report to generate a few report form a IEnumerable object. I need to generate a Link like this

PDF - http://myserver.com/reports/ProductsReport.pdf

The Question is how do I do this?

En Stop Using Doddle Report, and generate del Excel in XML format.

Upvotes: 4

Views: 33752

Answers (4)

Adriano Galesso Alves
Adriano Galesso Alves

Reputation: 819

I'd done something similar what you want on MVC 5 and I used FilePathResult as J.W said.

cshtml:

@Html.ActionLink("Download Here", "DownloadExampleFiles", "Product", new { fileName = "variation-example" }, new { @target = "_blank" })

ProductController:

public FilePathResult DownloadExampleFiles(string fileName)
{
    return new FilePathResult(string.Format(@"~\Files\{0}", fileName + ".txt"), "text/plain");
}

Download a file seems to be very silly/easy, however, for those who are new on MVC, it's not. This approach sounds to be the best while using MVC.

PS: I've forced a .txt just as an example. You should do what is intersting for you to get the specific file.

Upvotes: 6

J.W.
J.W.

Reputation: 18181

Check out this tutorial to return different action result.

The ASP.NET MVC framework supports several types of action results including:

  • ViewResult – Represents HTML and markup.
  • EmptyResult – Represents no result.
  • RedirectResult – Represents a redirection to a new URL.
  • JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  • JavaScriptResult – Represents a JavaScript script.
  • ContentResult – Represents a text result.
  • FileContentResult – Represents a downloadable file (with the binary content).
  • FilePathResult – Represents a downloadable file (with a path).
  • FileStreamResult – Represents a downloadable file (with a file stream).

Upvotes: 17

darren
darren

Reputation: 193

Something like this maybe:

<h2>List Of Reports</h2>
<ul>
    <% foreach (var report in Model){ %>
        <li><a href="<%= Html.BuildUrlFromExpression<ReportController>(r => r.Reports(report.Filename)) %>"><%=report.Filename %></a></li>
    <% } %>
</ul>

There maybe a shorter way but this works.

Upvotes: 0

Dave Swersky
Dave Swersky

Reputation: 34810

AFAIK, there is nothing special about doing this in MVC. Create a LinkButton on your form with a handler that generates the PDF file, then redirect to the created file.

Upvotes: 0

Related Questions