1

I have page where I use model which can have different types (depending by action and controller). My problem starts when I want to use partial which take parameter from Model like:

@Html.Partial("~/Views/Components/SubMenu.cshtml", MyProject.Web.MenuHelper.GetSubMenu(Model.field1))

but, if I not declare type of model I have an error like Partial can not use dynamic values. So I have idea to solve it with:

@if (Model.GetType() == typeof(ContentPage))
{
    @model ContentPage
    @Html.Partial("~/Views/Components/SubMenu.cshtml", MyProject.Web.MenuHelper.GetSubMenu(Model.field1))
}
else if (Model.GetType() == typeof(Data.Models.Directory))
{
    @model Directories
    @Html.Partial("~/Views/Components/SubMenu.cshtml", MyProject.Web.MenuHelper.GetSubMenu(Model.field2))
}

But then I have error like: ContentPage.field2 no exist.

Do you have any ideas how can I solve it?

Any help would be appreciated.

Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62
  • 1
    when ever you find yourself testing the type of an object (especially for control flow) think "Might I have a design issue?" – Rune FS Jun 14 '12 at 09:09

1 Answers1

0

It's not a good idea to strongly type a view or a partial view with different models based upon conditions. If you still want to use different kind of models in a view/partial view then you have to go for ViewData/ViewBag approach.

The other option is you can go for generic view models see this thread.

Community
  • 1
  • 1
VJAI
  • 32,167
  • 23
  • 102
  • 164