File Result in Controller Sample in MVC: Day 15

Introduction

This article shows how to use a File result in a controller in MVC.

Step 1

Create a MVC project from the "Empty" template. Right-click on "Controllers" and select "Add" >> "Controller...".

Adding New Controller in MVC

Step 2

Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.

Adding MVC 5 Empty Controller

Step 3

Name the controller as in the following:

Specifying Controller Name

And it will add an action result method to the controller.

Index Action Result

Step 4

Now we need to create a view. Right-click on "Index" and select "Add View...".

Adding View

Step 5

Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

Specifying View Name

Step 6

Add a title to the index page.

Index Cshtml page

Step 7

Create a folder "File" and save a Word document to test the FileResult sample.

Creating New Folder

Step 8

Filepathresult initializes a new instance of the filepathresult class by using the specified file name and content type.

Using HttpGet Attribute

Step 9

Create a link to call the downloadfile() method of the home controller.

Creating ActionLink

Step 10

Run the project, click on "Download Word File" and it will download the Word file. You can find the file in the download folder.

Downloading File

Downloaded File

Step 11

The file creates a filepathresult object using file name and content type. So create another action method and return the file.

Code to Download File

Step 12

Create a link to call the downloadTextFile() method of the home controller.

Creating Link

Step 13

Run the project, click on "Return File" and the text file will be opened in the browser.

Index View

Calling Index View

<< Day 14                                                                                >> Day 16

Up Next
    Ebook Download
    View all
    Learn
    View all