What is the best way to use multiple models with sames properties and use a single view?

advertisements

For example, I have 3 models with an Id (int), a Name (string) and an active (bool). It's possible to use just one view for these models with the same properties ? A technique like a generic object ? Inheritance ? It's to avoid to write multiple views with the same HTML code.


You could create a ViewModel.

For sample:

public class CustomerViewModel
{
   public int Id { get; set; }
   public string Name { get; set; }
   public bool Active { get; set; }
}

And create another ViewModel with a type like this:

public class CustomersViewModel
{
    public CustomerViewModel Customer1 { get; set; }
    public CustomerViewModel Customer2 { get; set; }
    public CustomerViewModel Customer3 { get; set; }
}

and type your view with this type:

@model CustomersViewModel

Or just use an collection to type your view

@model List<CustomerViewModel>

Take a look at this anwser! https://stackoverflow.com/a/694179/316799