Search code examples
asp.net-mvcrazordownloadfilecontentresult

Url.Action download action causes new tab to open/close quickly before download


I have some code that calls a controller in razor view like

<a target="_blank" href='@Url.Action("ViewFile", "Form", new { id = item.Id })'>
   <i class="fa fa-download" aria-hidden="true"></i>&nbsp;@item.Title
</a>

The controller action returns a FileContentResult

It all works fine, the only issue is the download causes a tab to quickly open and then close (google chrome).

I need the file to be able to download without the tab opening.


Solution

  • You are explicitly specifying to open a new tab/page by using target="blank".

    From MDN:

    target

    Specifies where to display the linked URL. It is a name of, or keyword for, a browsing context: a tab, window, or <iframe>.

    • _blank: Load the URL into a new browsing context. This is usually a tab, but users can configure browsers to use new windows instead.

    Remove that attribute, and it won't open a new tab/page.

    <a href='@Url.Action("ViewFile", "Form", new { id = item.Id })'>
       <i class="fa fa-download" aria-hidden="true"></i>&nbsp;@item.Title
    </a>