As a fairly experienced ASP.Net developer who recently started using MVC, I try to change my thinking a bit with the traditional “server and event handler” management method in a more dynamic way of MVC. I think I get there slowly, but sometimes MVC "magic" casts me away.
My current scenario is to create a web page that allows the user to view the local file, upload it to the server, and repeat this until it has a list of files to work with. When he is satisfied with the list of files (which will be displayed in the grid on the page), he will click a button to process the files and extract some data that will be stored in the database.
The last part is not so important, now I'm struggling with something as trivial as creating a list of files and saving this list between requests. In a traditional approach, this would be extremely simple - data would be stored in the ViewState. But in MVC, I need to transfer data between the controller and the views, and I do not fully understand how this should work.
I think I'd rather post my rather incomplete attempt to encode this to explain the problem.
To save the file list data, I created a view model, which is a typed file list, as well as some additional metadata:
public class ImportDataViewModel { public ImportDataViewModel() { Files = new List<ImportDataFile>(); } public List<ImportDataFile> Files { get; set; } ...
In the view, I have a form for viewing and downloading a file:
<form action="AddImportFile" method="post" enctype="multipart/form-data"> <label for="file"> Filename:</label> <input type="file" name="file" id="file" /> <input type="submit" /> </form>
The view uses the viewmodel as its model:
@model MHP.ViewModels.ImportDataViewModel
This will send the file to my action:
public ActionResult AddImportFile(HttpPostedFileBase file, ImportDataViewModel importData) { if (file.ContentLength > 0) { ImportDataFile idFile = new ImportDataFile { File = file }; importData.Files.Add(idFile); } return View("DataImport", importData); }
This action returns a view for the DataImport page along with a viewmodel instance containing a list of files.
This works well until a certain point, I can view the file and load it, and I can see the viewmodel data inside the action, and then also, if I put a breakpoint in the view and debug "this.Model", everything is fine.
But then, if I try to load another file, when setting a breakpoint inside the AddImportFile action, the importData parameter is empty. Thus, the view obviously does not pass the current instance of its model to the action.
In the MVC samples I went with, an instance of the model is “magically” passed to the action method as a parameter, so why is it now empty?
I assume the real problem is my limited understanding of MVC and that this is probably a very simple solution. In any case, I would be extremely grateful if someone could point me in the right direction.