0

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?

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
andrey1567
  • 97
  • 1
  • 13

3 Answers3

2

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);
}
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

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);
Zabavsky
  • 13,340
  • 8
  • 54
  • 79
0

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();
ekad
  • 14,436
  • 26
  • 44
  • 46