Reputation: 139
Model:
public class Service
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
ViewModel:
public class FullPrice
{
public IEnumerable<Service> Services { get; set; }
}
View:
@model hotel.Models.FullPrice
@foreach(Service service in Model.Services)
{
//
}
My view model is NULL. Why?
Upvotes: 0
Views: 460
Reputation: 14624
Change your ViewModel code to below
public class FullPrice
{
public FullPrice()
{
this.Services = new List<Service>();
}
public IEnumerable<Service> Services { get; set; }
}
so the Services
property won't be null when you do this
FullPrice model = new FullPrice();
Upvotes: 0
Reputation: 30607
Model would be NULL because there is no currently existing instance as the view is being executed.
Usually, the way to pass a model instance into a view would be in the corresponding action method like
public View myActionMethod()
{
hotel.Models.FullPrice model = new hotel.Models.FullPrice();
model.Services = new List<Service>();//Also prevent NULL exception with this property
return View(model);
}
Upvotes: 2
Reputation: 13640
I guess it's not the model what is null, but the Services
. Change the action code to
FullPrice model = new FullPrice
{
Services = new List<Service>()
};
return View(model);
Upvotes: 1