MVC ViewModel-未将对象引用设置为对象的实例 [英] MVC ViewModel - Object Reference Not Set to Instance of an Object

查看:275
本文介绍了MVC ViewModel-未将对象引用设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将DataTable转换为包含行和列的视图模型时,收到未将对象引用设置为对象实例"错误.

I receive an "Object reference not set to instance of an object" error while trying to convert a DataTable into a viewmodel containing rows and columns.

public class ViewModel
{
        public List<ColumnViewModel> Columns { get; set; }
        public List<RowViewModel> Rows { get; set; }
}

    public class ColumnViewModel
    {
        public string Name { get; set; }
    }

    public class RowViewModel
    {
        public List<CellValueViewModel> Values { get; set; }
    }

    public class CellValueViewModel
    {
        public string Value { get; set; }
    }

型号

    ViewModel myViewModel = new ViewModel();
    CellValueViewModel myCellValueViewModel = new CellValueViewModel();
    RowViewModel myRowViewModel = new RowViewModel();
    foreach (DataColumn column in GridData.Columns)
    {
        ColumnViewModel myColumnViewModel = new ColumnViewModel();
        myColumnViewModel.Name = column.ColumnName;
        myViewModel.Columns.Add(myColumnViewModel);
    }

错误发生在myViewModel.Columns.Add(myColumnViewModel); 我不明白为什么会这样,因为我已经实例化了我在这里使用的每个对象.

The error occurs at myViewModel.Columns.Add(myColumnViewModel); I do not understand why this is happening since Ive instantiated each object that Im using here.

推荐答案

好吧,您从未为Columns属性分配值.尝试将值添加到此列表之前,请确保已实例化它:

Well, you never assigned the Columns property a value. Make sure you have instantiated it before attempting to add values to this list:

ViewModel myViewModel = new ViewModel();
myViewModel.Columns = new List<ColumnViewModel>();

这篇关于MVC ViewModel-未将对象引用设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆