Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parameters to a @Url.Action() call from JavaScript on click

I have a link that when clicked needs to call a controller action with certain data which must be retrieved via JavaScript. The action will be returning a FileStreamResult.

I looked at @Url.Action but I couldn't figure out how (or even if) I could pass value dictionary stuff which had to be retrieved via JS.

So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.

So any help on how you would do something like this would be great..

like image 800
Shane Courtrille Avatar asked Mar 16 '11 21:03

Shane Courtrille


1 Answers

So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.

Exactly. You can't do much with a received byte in javascritpt: obviously you cannot save it on the client computer nor pass it to some external program on the client. So don't call actions that are supposed to return files using AJAX. For those actions you should use normal links:

@Html.ActionLink("download file", "download", new { id = 123 })

and let the user decide what to do with the file. You could play with the Content-Disposition header and set it to either inline or attachment depending on whether you want the file to be opened with the default associated program inside the browser or prompt the user with a Save File dialog.


UPDATE:

It seems that I have misunderstood the question. If you want to append parameters to an existing link you could subscribe for the click event in javascript and modify the href by appending the necessary parameters to the query string:

$(function() {
    $('#mylink').click(function() {
        var someValue = 'value of parameter';
        $(this).attr('href', this.href + '?paramName=' + encodeURIComponent(someValue));
        return true;
    });
});
like image 55
Darin Dimitrov Avatar answered Sep 18 '22 15:09

Darin Dimitrov