Search code examples
c#asp.net-mvc-4model-view-controllergetter-setter

Why can't I update my variables from my Model in my Controller using C# MVC


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?


Solution

  • 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);