Ksingh
Ksingh

Reputation: 45

Opening a file in a new tab of the web browser

I have a view which shows a list of xml files in a directory. Also i have a button which would display the content of the file name selected in the browser. Currently its showing the content in a the same tab. But i want to display it in a new tab of the browser.. for example if i select two file names from the list, then it should open different tab for both the files.. Please find the code below.

public ActionResult ViewFile(string[] Name)
{
byte[] ImageData = null;

for (int i = 0; i < Name.Length; i++)
{

string filepath = holdpath + @"\" + Name[i];
string result;
using (StreamReader streamReader = new StreamReader(filepath))
{
result = streamReader.ReadToEnd();

}
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();

Paragraph paragraph = new Paragraph();
paragraph.Add(result);
document.Add(paragraph);

document.Close();
ImageData = memoryStream.ToArray();
}


}
Response.AppendHeader("Content-Disposition", "inline; filename=MyFile.pdf");
return File(ImageData, "application/pdf");
}

Please note that i am using itextsharp because the file also needs to be downloaded as pdf if required

I have added the View here

@model IEnumerable<FileInfo>
@{
ViewBag.Title = "files";
}

<h2>Held files</h2>
@using (Html.BeginForm())
{
<div style="border:solid;width:100%;overflow-x:auto;">
<table  align="center" style="width:100%">
<thead>
<tr>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (FileInfo file in Model)
{
<tr>

<td>
<input type="checkbox" name="Name" value="@file.Name" />
@file.Name
</td>
<td>
@Html.ActionLink("View", "ViewFile", "HoldFiles", new { Name = file.Name }, 
new { @class = "btn btn-primary btn-sm", target = "_blank" })

</td>        
</tr>

}
</tbody>
</table>
</div>
}

Upvotes: 0

Views: 2027

Answers (1)

SᴇM
SᴇM

Reputation: 7213

In your view, put target="_blank" on your anchor element.

For example:

<a href="https://www.url.com" target="_blank">Open in new tab</a>

or if using razor:

@Html.ActionLink("Text", "ActionMethodName", "ControllerName", new { id = Model.Id }, new { @class = "btn btn-primary btn-sm", target = "_blank" })

Upvotes: 3

Related Questions