8

I have two partial views which are exactly the same, but for the @model.

@model Project.Models.X

@model Project.Models.Y

How could I pass this model type to the view so that I can use the same view for both?

TheGwa
  • 1,919
  • 27
  • 44

4 Answers4

5

Not sure if this is best practice, but you could also use HTML.RenderAction to call your controller and have it return a PartialViewResult with whatever model you want, like so:

  @{Html.RenderAction("MyPartialAction", "MyController", new { someID = 1 });}

and

 public PartialViewResult MyPartialAction(int? someID)
 {
        return PartialView("MyPartial",SomeModel);
 }
mymex1
  • 148
  • 3
3

You can create a ViewModel Z, which passed to View. If you want to pass model X or Y, just passed that to Z then pass model Z to View.

gandil
  • 5,398
  • 5
  • 24
  • 46
2

Make both classes implement the same interface, and use the interface as your model.

As suggested by Tim: If possible you could also inherit from the same base class. Although this is not always possible, using the interface approach is mostly possible.

GvS
  • 52,015
  • 16
  • 101
  • 139
1

Mostly like gandil: Create a ViewModel Z but use Automapper to map from Y and X. That way you can keep your UI models clean and DRY.

John Landheer
  • 3,999
  • 4
  • 29
  • 53