Using .net Core, MVC, C#
I have created a single model that contains 2 separate models. Code as below:
public abstract class ViewModelBase
{
public string Environment { get; set; }
}
public class CombinedViewModel : ViewModelBase
{
public FirstViewModel FirstViewModel { get;set;}
public SecondViewModel SecondViewModel { get; set; }
}
public class FirstViewModel : ViewModelBase
{
public string FirstName{ get;set;}
public string LastName{ get; set; }
}
public class SecondViewModel : ViewModelBase
{
public string Mode { get;set;}
}
Here is my MVC Controller:
public IActionResult Index(string environment, string mode)
{
var model = new CombinedViewModel ();
model.Environment = environment;
model.SecondViewModel.Mode = mode;
return View(model);
}
What I have searched it that this is way to initialize multiple model. Not sure what I am doing wrong here but I get the below error:
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
model.SecondViewModel.Mode = mode;
Do I need to initialize my first and second model separately. Please note that I am still not using my "mode" in my view yet.