Asp.net mvc 2 multiple partial view

I have a contoller that displays 3 different views. But I also have a common part (div) for each point of view. I thought I could create a UserControl with my own controller and include that control in my views (new controller and view as controll).

How do I use this UserControl? Should there be a partial view? Or another approach - can I have multiple partial views on the same page?

I have searched the internet the last days of browsing and have not found a working solution that works for me. Also I want to use strongly typed views / data.

Greetings

+2


a source to share


1 answer


You must use a partial view. Then you call <% Html.PartialRender("MyCommonControl", Model); %>

in 3-4 views to display the general section (like a menu or whatever).

This way you can strictly enter a partial view and pass the model (like in the example above) or the part of the model that is relevant to it.

UserControls is an ASP.NET Forms paradigm, you should use partial views because they are using the same MVC View Engine.

Update

If you put a PartialView in /Views/Home

, it will only be available to HomeController

. You want to put it in /Views/Common

to make it available to ALL controllers.

You should also make a Generic ViewModel for the data you want to manage and make it a subcomponent of the models for each controller:

For instance:



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 also override the control

Having the following files:

  • /Views/Common/MyCommonControl.ascx

  • /Views/Products/MyCommonControl.ascx

When called .RenderPartial("MyCommonControl")

from ProductsController

# 2 and from any other controller, # 1 is used. So you can override the functionality for some controllers if you like.

+2


a source







All Articles