JBoom JBoom - 1 year ago 56
C# Question

MVC PartialView in multiple Views with different models

This may be a silly question and is more of a question about how to do something rather than an actual coding issue.

I want to have a partial view which contains a search form and search results and uses model


This partial view would then be rendered in multiple views that use different models.

Is it possible for me to this or do I have to create the search form within each view or create a partial view for each view so that the view and partial view use the same model?

If I use the
model for the partial view and another model for the view I just get error:

The model item passed into the dictionary is of type 'x', but this dictionary requires a model item of type 'y'.

Answer Source

You can definitely do that with different implementations.

First Option:

You can drop the Model from the "Shared" view that you have and have it work with a ViewBag or ViewData that you pass to the view from your controllers. Obviously you will need to populate this view bag or view data within all the controller actions that will return this shared partial view.

Second Options:

Instead of having Suppliers as the view model of the shared view, you can have another property in the view model "Supplier" that you can use, but when you are rendering the shared view you need to specify the property and pass it as the Model to the shared view like:

Html.RenderPartial("MySharedView", Model.SharedViewModel);

Now you have to do the same thing for all other views that render this shared and basically have this "SharedViewModel" as a property in those view models and pass the Model.SharedViewModel to the shared view.

For sure there are other options too that you can find out once you get more comfortable with Shared Views in MVC.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download