I have a submenu I want to display only when certain controllers are used and a certain model is present. I created a partial and tried to render it in the _Layout.cshtml but I get an error stating model item passed is of type … but this dictionary requires item of type…
I could put the menu in each of my views for the controllers with the right type of model being passed but that seems like the less flexible way.
Currently I am checking if my model is null in the _submenu partial
@if(Model != null)
However, this will let any type of model through and then when it is the wrong type it errors.
I thought the best way would be to specify that my @Html.Partial is only run when certain controllers are used. Or Is there a way to verify the model type so the code doesn’t run if the model passed to the view is incorrect?
It sounds like you need your model to be dynamic (Check this website for more information on this), then on your view you can just check the type of the model and act accordingly:
Note: Original example taken from the website mentioned above.