0

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Kénium
  • 105
  • 1
  • 10
  • You should be able to use either inheritance or an Interface that each of the three models utilizes and then specify either the Interface or the Base (parent) class as the strongly-typed model for the view. – David Tansey Apr 05 '13 at 17:17

3 Answers3

2

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

Community
  • 1
  • 1
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
1

In a view you can either

  • specify shared base class for all models and use that.
  • use dynamic as model
  • split view in shared (extract into separate view) and specific part. Than call shared sub-view with either existing model (if using base class/dynamic) or simply new model constructed based on data in specific model.

Sample of extracting shared portion with inheritance. Using Html.Partial to render shared portion:

class SharedModel { /* Id,...*/ }
class SpecificModel : SharedModel { /* Special... */ }

SpecificView:

@model SpecificModel 
@Html.Partial("SharedView", Model)
<div>@Model.Special</div>

SharedView:

@model SharedModel 
<div>@Model.Id</div>

Side note: You can specify view name when returning result by using View if view name does not match action name:

return View("MySharedView", model);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

In ASP.NET MVC4 you have the opportunity not to define a model for the view. This means leave the definition of the model empty (don't use @model MyNamespace.MyClass) and then it will automatically use "dynamic" as model.

Greetings Christian