Ad

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

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?

Ad

Answer

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 = Model.docs[i].id })" class="rowFile">

and change the script to

$('.rowFile').click(function() {
    var urlDownload = $(this).data('url');
});
Ad
source: stackoverflow.com
Ad