I have an upload function in an MVC 3 project which store the files in a database. I am trying to write code that will list all the files in the database with a link to download each one, but I have not having much success. Here is the controller code:
public ActionResult Download(int id)
{
var db = GetDataContext();
var file = db.UserFiles.First(f => f.ID == id);
return File(file.Data.ToArray(), "application/octet-stream", file.Name);
}
public ActionResult Index()
{
var db = GetDataContext();
var files = db.UserFiles.Select(f => new FileViewModel { ID = f.ID, Name = f.Name });
return View(files);
}
I have created a view from the ActionResult Index and the code in the view is:
@Html.ActionLink("Lesson", "Download", "Upload", new { id = 1 })
I have also created a class file called FileViewModel, which serves to prevent the data being retrieved from the database when the files are listed:
public class FileViewModel
{
public int ID { get; set; }
public string Name { get; set; }
}
And in the download View where I will list the files, I have:
@model IEnumerable<DFPProductions_Default.Models.FileViewModel>
The error I’m getting when I click on the link is:
The parameters dictionary contains a null entry for parameter ‘id’ of non-nullable type ‘System.Int32’ for method ‘System.Web.Mvc.ActionResult Download(Int32)’ in ‘DFPProductions_Default.Controllers.UploadController’.
Please help me discover what I’ve done wrong.
Thanks,
Amy
The problem seems to be you are not sending any Id to the Controller.
Try calling you action link:
@Html.ActionLink("Lesson", "Download", "Upload", new { id = 1 }, null)Also, for future reference, you should keep the controller to a minimum, no interactions with the database.