I have a contoller that renders 3 different views. But I also have a common part (div) for every view. I thought that I can create an UserControl with own controller and include that control on my views (New controller and view as controll).
How should I use that UserControl? Should it be a partial view?
Or different approach – can I have multiple partial views on one page?
I’ve been searching the web for the last view days and haven’t found working solution that suits me. Also I want to use Strongly Typed views/data.
Cheers
You should use a partial view. Then you call
<% Html.PartialRender("MyCommonControl", Model); %>in the 3-4 views to render the common section (like a menu or something).This way you can strongly type the partial view and pass the model (like in the above example) or part of the model to it that is relevant.
UserControls are a ASP.NET Forms paradigm really, you should use partial views because they use the same MVC View Engine.
Update
If you place the PartialView in
/Views/Homeit’ll only be accessible to theHomeControllerYou want to put it in/Views/Commonto make it accessible to ALL controllers.You should also make a Generic ViewModel for The data that control needs, and make it a sub-component of the models for each Controller:
Eg:
Then in your Views for your controllers you call the partial render like this:
Note: You can override the control as well
Having the following files:
/Views/Common/MyCommonControl.ascx/Views/Products/MyCommonControl.ascxWhen you call
.RenderPartial("MyCommonControl")fromProductsController#2 is used, and from any other controller, #1 is used. So you can override functionality for some controllers if you wish.