Pregunta

I have a dropdown list and a link next to the dropdown list. When the button is clicked, I want an action to be invoked on the controller so I can download my file by the SelectedFileId selected in the dropdown list. The problem is, when I view the link url in the console, it is only

http://localhost/Download/DownloadFileById

Which isn't including my parameter. I assume that is because Model.SelectedFileId is null when the html is generated. Is there a way I can get that URL to be dynamic and change whenever I change the dropdown?

My code:

@Html.DropDownListFor(x => x.SelectedFileId, Model.FileIds)
@Html.ActionLink("Download File", 
                 "DownloadFileById", 
                 "Download", 
                 new { fileId = Model.SelectedFileId })
¿Fue útil?

Solución

If I understand the question correctly, you want to be able to select an item in the drop down list and pass that value as a parameter to your server side action.

That wont work without javascript. Setting Model.SelectedFileId will only set the FileId value at the time the page was rendered. After that it is all client side, which means you will need javascript.

The easiest thing to do is a simple javascript method. Instead of using an ActionLink, create a basic html link or button, and give it an onclick handler.

@Html.DropDownListFor(x => x.SelectedFileId, Model.FileIds, new {id = "FileDownloadList"}) //Give this an id so you can select it later. Also assuming FileIds is a SelectList.
<input type=button onclick="DownloadFile" value="Download File"/> 

Then you need to write the javascript, which takes the selected id and sends it to your action method server side. I am not going to use ajax because I don't think you can just download a file using ajax. You can, however, do what the ActionLink would have done and direct the browser to your file.

function DownloadFile(){
   var fileID = $("#FileDownloadList").val(); //Get selected FileID
   window.location = "http://localhost/Download/DownloadFileById?fileId=" + fileId; //Redirect to file. I am using the full path, but you could use a relative path.
}

This should perform the same action as the ActionLink, but dynamically select whatever value you have in the drop down list.

Otros consejos

You're using the wrong overload for ActionLink. You're using this one

which looks like

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    Object routeValues,
    Object htmlAttributes
)

but you want this one, which would look like:

@Html.ActionLink("Download File", 
             "DownloadFileById", 
             "Download", 
             new { fileId = Model.SelectedFileId },
             null)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top