asp.net mvc 2 multiple partial view
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 controll开发者_Go百科er 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/Home
it'll only be accessible to the HomeController
You want to put it in /Views/Common
to 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:
class CommonSectionViewModel
{
public string Data { get; set; } // Just Example Data
public int Count { get; set; }
}
class ProductsModel
{
public CommonSectionViewModel CommonData { get; set; }
// Other properties for a products models
}
class CompaniesModel
{
public CommonSectionViewModel CommonData { get; set; }
// Other properties for a company model
}
Then in your Views for your controllers you call the partial render like this:
<% Html.PartialView("MyCommonControl", Model.CommonData); %>
Note: You can override the control as well
Having the following files:
/Views/Common/MyCommonControl.ascx
/Views/Products/MyCommonControl.ascx
When you call .RenderPartial("MyCommonControl")
from ProductsController
#2 is used, and from any other controller, #1 is used. So you can override functionality for some controllers if you wish.
精彩评论