0

I have a viewmodel as such

    public class NoteViewModel
    {
      public tblNotes tblnote { get; set; }   
    }

In my controller, I do the following next after doing a build so my controller knows about the viewmodel:

    NoteViewModel viewModel= new NoteViewModel();

    viewModel.tblnote.NoteModeID  = 1234; // get error here

    return PartialView(viewModel);

I get the following error though:

{"Object reference not set to an instance of an object."}

tereško
  • 58,060
  • 25
  • 98
  • 150
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

2 Answers2

0

What exactly is tblNotes? If it is a reference type, than viewModel.tblNote is null after the first line of code is executed.

twoflower
  • 6,788
  • 2
  • 33
  • 44
0

What is the type tblNotes? (Side note: In C# class names should begin with a capital letter as a matter of convention.)

Since this is a custom type and, thus, a reference type, its default value is null. So when you instantiate a new NoteViewModel it's going to set all of its members to their default values unless otherwise specified. Since that value is null, you can't use it here:

viewModel.tblnote.NoteModeID = 1234;

Without knowing more about your types, the simple answer is to just instantiate that member in the view model's constructor:

public class NoteViewModel
{
    public tblNotes tblnote { get; set; }

    public NoteViewModel()
    {
        tblnote = new tblNotes();
    }
}

This way the object will be instantiated any time a view model is created, so you can use it.

David
  • 208,112
  • 36
  • 198
  • 279