为什么我不能使用 C# MVC 从我的控制器中的模型更新我的变量

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

我正在尝试 运行 我的控制器中的更新过程,并尝试从我的模型中访问值,这是我的控制器中的代码

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

这就是我在模型中设置变量的方式

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

当代码 运行s 尝试更新 groupIdx 列表时出现错误 'NullReferenceException unhandled by user' 我做错了什么?

据我所知 - 你没有初始化 model.groupIdx 因此它仍然是 null - 这就是你得到 NullReferenceException

的原因

应该是这样的

TaskViewModel model = new TaskViewModel();                       
model.groupIdx = new List<int>();
model.groupIdx.Add(id);

您的groupIdx仍为空,未初始化。要么在初始化它的模型中添加一个构造函数,要么在创建对象时设置它。

model.groupIdx = new List<int>();