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.”}
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 newNoteViewModelit’s going to set all of its members to their default values unless otherwise specified. Since that value isnull, you can’t use it here:Without knowing more about your types, the simple answer is to just instantiate that member in the view model’s constructor:
This way the object will be instantiated any time a view model is created, so you can use it.