Reputation: 1413
I have a function in my MVC controller which downloads a file, I need it to do this when its passed a filename. This function works, but the file name is an AgularJS value.
MVC Method:
public ActionResult DownloadFile()
{
string fileName = "test.txt";
string path = AppDomain.CurrentDomain.BaseDirectory + "/UploadedFiles/";
byte[] fileBytes = System.IO.File.ReadAllBytes(path + fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
This works when called using:
@Html.ActionLink("Click here to download", "DownloadFile", new { })
I need to pass a string to the method however to use as "fileName".
Updated Method to accommodate receiving fileName:
public ActionResult DownloadFile(string fileName)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "/UploadedFiles/";
byte[] fileBytes = System.IO.File.ReadAllBytes(path + fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Ways I've tried calling this methods while passing an agular value are as follows:
1)
@Html.ActionLink("Download File", "DownloadFile", new { id = "{{file}}" })
This way causes an exception in the method as "fileName" is null so the filepath doesn't resolve for the download.
2)
@Html.ActionLink("Download File", "DownloadFile", "Home", new { id = "{{file}}" })
Practically the same as the fist, but specifying the controller name, gives same result as the first.
3)
@{
var url = Url.Action( "DownloadFile2", "Home", new { id = "{{file}}" });
url = HttpUtility.UrlDecode(url);
}
<a data-ng-href="@url">Download File</a>
This results in the browser going to page with URL: http://localhost/Home/DownloadFile/test.txt with page error: HTTP Error 404.0 - Not Found
The view can see the value and can output it to the page as plain text, but I can't figure out how to send the value to the method.
Upvotes: 0
Views: 56
Reputation: 12452
As you have the following signature for your action:
public ActionResult DownloadFile(string fileName)
You should always send the parameter named fileName
no matter if you're using Url.Action
or ActionLink
.
@Html.ActionLink("Download File", "DownloadFile", "Home", new { fileName = "{{file}}" })
var url = Url.Action( "DownloadFile2", "Home", new { fileName = "{{file}}" });
id
is used as a generic parameter only when you define your supported routes:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
// Parameter defaults
);
There you can control if id can be optional or not and many other things.
Upvotes: 1