0

Hi I'm having a problem and I just can't seem to get it around. I want to populate part of my model then pass it to the view so the user can populate the rest and submit.

Here's the model

public class SelectModel
{
    public List<String> Scripts { get; set; }
    public string ScriptSelection { get; set; }
    public IFormFile InputFile { get; set; }

}

and here's where I'm trying to populate the list in the controller

    public IActionResult Index()
    {
        SelectModel model = new SelectModel();

        model.Scripts.Add("Germany");

        return View(model);
    }

I'm getting null ref exception at model.Scripts.Add("Germany");

I've populated a model from a view and passed it back to a controller before but I seem to be having issues initialising the model in the controller for my 1st view

Javrel
  • 5
  • 3

2 Answers2

3

Because you are calling Add method on NULL . model.Scripts is NULL and hence you are getting the classic "Object Reference not set to an instance" error

Initialize it to an empty list before trying to add to it.

One way is to have a default constructor, which initialize your Scripts property to an empty list.

public class SelectModel
{
    public List<String> Scripts { get; set; }
    public string ScriptSelection { get; set; }
    public IFormFile InputFile { get; set; }

    public SelectModel()
    {
      this.Scripts =new List<string>();
    } 

}

Another option is to initialize it to an empty list when you create the object

var model = new SelectModel(){ Scripts =new List<string>() };
model.Scripts.Add("Germany");

You can also use the object/collection initializator syntax as well

var model = new SelectModel()
{
    Scripts = new List<string>()
    {
        "Germany", "USA"
    }
};
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • doh! thanks, seem to have just had a blind spot there for a few hours, seemed to have thought creating the model also created the things in it. – Javrel Oct 26 '17 at 15:00
2

You have to initialize the list. Something like

public class SelectModel
{
    public List<String> Scripts { get; set; } = new List<String>();
    public string ScriptSelection { get; set; }
    public IFormFile InputFile { get; set; }

} 

or inside the controller action

public IActionResult Index()
    {
        SelectModel model = new SelectModel();
        //initialization of the list Before usage
        model.Scripts = new List<String>();
        model.Scripts.Add("Germany");

        return View(model);
    }
Iza Atsou
  • 181
  • 2
  • 6