1

I'm trying to run an update process in my Controller and in doing so trying to access values from my Model, this is the code in my Controller

    [HttpGet]
    [Authorize]
    public void updateNewGroup(int id)
    {
        int incomingID = id;
        TaskViewModel model = new TaskViewModel();                       
        model.groupIdx.Add(id);            
    }

This is how I've set up my variable in my Model

    public List<int> groupIdx { get; set; }

When the code runs and it attempts to update groupIdx list I get an error 'NullReferenceException unhandled by user' what am I doing wrong?

user616076
  • 3,907
  • 8
  • 38
  • 64

2 Answers2

1

As far as I can see - you're not initializing model.groupIdx thus it remains null - that's why you're getting NullReferenceException

It should be something like

TaskViewModel model = new TaskViewModel();                       
model.groupIdx = new List<int>();
model.groupIdx.Add(id);
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • Both answers were correct, thank you. The only other problem is that each time the updateNewGroup method is called groupIdx is always null and never retains it's value. How do I get it to persist? – user616076 Dec 01 '15 at 10:15
  • @user616076 of course `groupIdx` is null each time you're calling `updateNewGroup` because you're creating new model each time in the very beginning of this method. If you need to somehow store this `groupIdx` - it can be done by variable ways. You can store it in DB, some static field or something else - it's a broad question and it's hard to say more without knowing your application architecture and goals. – Andrey Korneyev Dec 01 '15 at 11:11
0

Your groupIdx is still null, it's uninitialized. Either add a constructor to the Model where you initialize it or set it when you create the object.

model.groupIdx = new List<int>();
Peter
  • 171
  • 4