File Result in Controller Sample in MVC

File Result in Controller Sample in MVC

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...".

image.png

Step 2

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

image.png

Step 3

Name the controller as in the following:

image.png

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

image.png

Step 4

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

image.png

Step 5

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

image.png

Step 6

Add a title to the index page.

image.png

Step 7

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

image.png

Step 8

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

image.png

Step 9

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

image.png

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.

image.png

image.png

Step 11

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

image.png

Step 12

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

image.png

Step 13

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

image.png

image.png

<< Day 14

>> Day 16