MVC c# ViewModel with table object
-
22-06-2021 - |
Frage
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."}
Lösung
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.
Andere Tipps
What exactly is tblNotes
? If it is a reference type, than viewModel.tblNote
is null
after the first line of code is executed.