1

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.

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

try

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

You have not initialized tipo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.