
July 24, 2018 07:46 by
Peter
In this post, we will learn about how to open PDF or other files in a new tab using C#. For this example, first we need to return a file from MVC Controller then open the file in a new tab from view. For this, I will set return type "FileResult" from MVC controller and return "File" with a byte Array of the file and its content type. Let's start coding.
Step 1
First, create a new project of MVC from File -> New -> Project.

Step 2
Select ASP.NET Web Application (.Net Framework) for creating an MVC application and set Name and Location of Project.

Step 3
After setting the name and location of the project, open another dialog. From this dialog select MVC project and click OK.

After creating a project create one controller method inside the home controller and name that "GetReport". and write the below code in this method.
Controller
public FileResult GetReport()
{
string ReportURL = "{Your File Path}";
byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);
return File(FileBytes, "application/pdf");
}
Above method returns FileBytes, and Content type is "application/pdf".
View
Create one function for an open PDF file in a new tab.
function GetClientReport() {
window.open('/{ControllerName}/GetReport, "_blank");
};
The above function will open a new tab in the browser and call controller GetReport() method and this method returns file ,and browser is displayed in an opened tab.
