Reputation: 602
The viewmodel I'm creating exists of one required class and depending on what page will be loaded another class is instantiated or perhaps another viewmodel. How would the implementation look like of this viewmodel?
public class ViewModel
{
public ViewModel()
{
foo = new Foo();
}
public Foo foo { get; set; }
public Bar1 bar1 { get; set; }
public Bar2 bar2 { get; set; }
public Bar3 bar3 { get; set; }
public OtherViewmodel otherVM { get; set; }
}
Based on the example above: Every view rendered by the razor engine needs an implementation of the class 'Foo'.
The first page needs the class 'Bar1'. The code in the controller would look like: ViewModel.Bar1 = new Bar1();
The second page will need the 'OtherViewmodel' class, and will create an instance in the controller of OtherViewmodel.
I don't know if this is the correct way of Object Oriented Programming. When a viewmodel doesn't need a certain object and it is a property of the class (but not instantiated), what about the size of the object?
For example the class 'ViewModel' would be used for all my page, so all my classes would be a property in this class. I think there is a cleaner way of programming this, but I haven't found it yet.
Any help would be appreciated. Thanks in advance.
Upvotes: 2
Views: 287
Reputation: 46641
How about using a base class?
public abstract class BaseViewModel
{
protected BaseViewModel()
{
foo = new Foo();
}
public Foo foo { get; set; }
}
You can derive classes from this one containing just one bar:
public class Bar1ViewModel: BaseViewModel
{
public Bar1 bar1 { get; set; }
}
This seems like a cleaner approach to me. You could also instantiate the Bar1
class in the derived class' constructor so you won't have to do this in the controller:
public Bar1ViewModel()
{
bar1 = new Bar1();
}
Upvotes: 3