views:

853

answers:

1

Hey Guys,

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

+1  A: 

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:

  1. /Views/Common/MyCommonControl.ascx
  2. /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.

Aren
Thanks Aren,That common section will contain data from DB query. If I have a separate controller for that view, shall I place that control to different folder rather than keep it the folder where other views are stored?
303
I've updated my examples to show you more :)
Aren
Thank you Aren!
303
I am getting there but despite the fact that I don't have any compilation errors, I get the YSOD:Object reference not set to an instance of an objectLine 13: foreach (var item in Model.FiguresList) {
303
I need some more code to tell you what's going wrong.Model may not be set.You should use `return View("MyView", modelObjectGoesHere);` when you launch your view in your controller.
Aren