PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

[FIXED] How use multitype Model in one layout (with partial)?

 May 18, 2022     asp.net-mvc, c#, model, partial     No comments   

Issue

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.


Solution

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.



Answered By - VJAI
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing