'List from ViewModel is empty in controller

Today I spotted very strange issue. I wrote app in .net core mvc.

I have two models:

public class Package{
public Int PackId{get; set;};
//some fields
public ICollection<Shipment> shipments{get; set;}//list with other models! 
}
public class Shipment{
Int Id{get; set;};
//some fields
[ForeignKey]
Int PackId {get; set;};
Package package{get;set;}

}

So as you can see one package has many shipments, but one shipment belongs only to one package (one to many relation).

Moreover I have also ViewModel:

AddViewModel{
//there are some fields from package
//and here are some fields from shipment
[BindProperty]
public ICollection<Shipment> shipments
}

My Controller method:

[HttpPost]
AddShipment(AddViewModel viewModel){
//some code here

return View(viewModel);
}

[HttpGet]
Add(){
var viewModel = new AddViewModel ();
return View("AddShipment",viewModel)}

And... everything in viewModel that coming from view is filled, but breakpoint shows that public ICollection<Shipment> shipments is null and it's very odd. Is something wrong? How to bind or flag that some inputs on view should be binded as next model in that list?



Solution 1:[1]

Try this:

[HttpGet]
Add() {
    var shipmentList = context.Shipments.ToList();
    var viewModel = new AddViewModel { shipments = shipmentList };
    return View("AddShipment", viewModel);
}

Solution 2:[2]

So, there is a solution. We need to create empty list in constructor. Otherwise there are some problems with nullpointer.

AddViewModel{
//there are some fields from package
//and here are some fields from shipment
public AddViewModel(){
shipments = new List<Shipment>();
}
[BindProperty]
public ICollection<Shipment> shipments
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andre Hofmeister
Solution 2 duckduckgoes