Download File From Database Using MVC Javascript Razor

I display the list of files, (in a database), that I could download in a table.

<table style="border: none; width:100%">                
    @for (int i = 0; i <= - 1; i++)
        <tr onclick="downloadFile('[i].id.ToString()')" class="rowFile" [email protected] [email protected]("rigaDoc" + i)>
            <td style="border-bottom:1px solid black; width:30px;">
                <img src="@Url.Content([i].icon)" alt="Image" />
            <td style="border-bottom:1px solid black; padding-left: 20px; width:auto;">
                @Html.Label([i].nameFile.ToString().Split('.')[0], new { @class = "" })

Once the user clicks on a row of that table, I need to send to the controller the GUID of that row and start the file download.

function downloadFile(fileId) {
    var urlDownload = '@Url.Action("Download", "GestioneDocumenti", new { id = fileId })';

However, I cannot use fileId because debugger says:

"the name fileId is not used in this context".

How can I send the information to the controller method?



Razor is server side code and is parsed on the server before it is sent to the view. Change your function to

function downloadFile(fileId) {
    var urlDownload = '@Url.Action("Download", "GestioneDocumenti")' + '/' + fileId;

A better solution would be to generate the url as a data- attribute

<tr data-url="@Url.Action("Download", "GestioneDocumenti", new { id =[i].id })" class="rowFile">

and change the script to

$('.rowFile').click(function() {
    var urlDownload = $(this).data('url');