Here is my view model:
public class AgencyViewModel
{
public int VendorId { get; set; }
public IEnumerable<Vendor> Vendors { get; set; }
public HttpPostedFileBase SpreadsheetFile { get; set; }
}
Here are my two controller methods:
public ActionResult Upload()
{
var viewModel = new AgencyViewModel
{
Vendors = _vendorsRepository.Vendors.OrderBy(v => v.Name)
};
return View(viewModel);
}
[HttpPost]
public ActionResult Upload(AgencyViewModel viewModel)
{
// do stuff
}
And my view:
@model MyModels.AgencyViewModel
@using (Html.BeginForm("Upload", "Agencies", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.DropDownListFor(model => model.VendorId,
new SelectList(Model.Vendors, "VendorID", "Name"),
"- Select a Vendor -")
@Html.TextBoxFor(model => model.SpreadsheetFile, new { type = "file" })
<p>
<input type="submit" value="Next" />
</p>
}
When I navigate to Upload, the Vendors are loaded correctly. But when I submit my form, my view model only contains VendorId and SpreadsheetFile, and Vendors is null.
I need to do some work with the Vendors collection after I submit the form, and I don’t want to load the all the data twice.
How can I keep the data in my view model?
You have to set your ViewData again, you can use an ActionFilter if you want to keep it DRY, another choice would be overriding the controllers OnActionExecuted method and loading your data there.
If you are doing good use of the MVC pattern you should only need to load the viewdata when the validation fails, since in that case you would load the same view again.