Guilherme Longo
Guilherme Longo

Reputation: 2308

nullReferenceException on nested models

I need help understand why I getting a null object reference here:

I have 2 models:

public class loadViewModel
{
    public importacaoConfig importacaoConfig { get; set; }
}

public class importacaoConfig
{
    public List<DocTypeModel> tipo { get; set; }
}

Im my controler I am passing a List to the model:

gedaiapp.Models.loadViewModel model = new gedaiapp.Models.loadViewModel();    
model.importacaoConfig.tipo = obj; -> Here obj is of type List<DocTypeModel>

This gives me:

System.NullReferenceException: Object reference not set to an instance of an object.

I have checked and the obj list has 3 elements. Which reference is null here? I don´t get it.

Upvotes: 1

Views: 558

Answers (3)

Bhushan Firake
Bhushan Firake

Reputation: 9448

try

importacaoConfig.tipo=new List<DocTypeModel>();

You have not initialized tipo

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

The problem is this:

model.importacaoConfig.tipo

You haven't instantiated importacaoConfig, so it's null (hence why you get the exception on that line.

Add this line to instantiate it (between your two existing lines):

model.importacaoConfig = new importacaoConfig();

So your controller would be:

gedaiapp.Models.loadViewModel model = new gedaiapp.Models.loadViewModel();
model.importacaoConfig = new importacaoConfig();    
model.importacaoConfig.tipo = obj;

Upvotes: 4

ChrisF
ChrisF

Reputation: 137108

You should really check in the debugger but I would assume that the following is null:

model.importacaoConfig

as you have not initialised it in when you create your loadViewModel.

You need to have a constructor that does the following:

public loadViewModel()
{
    importacaoConfig = new importacaoConfig();
}

I'd also think about giving your variables different names to the classes.

Upvotes: 1

Related Questions