Reputation: 67
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?
Upvotes: 0
Views: 593
Reputation: 67
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
}
Upvotes: 1
Reputation: 43860
Try this:
[HttpGet]
Add() {
var shipmentList = context.Shipments.ToList();
var viewModel = new AddViewModel { shipments = shipmentList };
return View("AddShipment", viewModel);
}
Upvotes: 2