ASP.NET MVC: Display dynamic data on master pages

If you play with the MVC 2 bits for a while you will come to a very simple question: How can I display dynamic data on my master page?

The structur of an MVC App (this is my demo app) :

image

Each controller has it´s own View-Folder and render the specific view (EntryController route to Views\Entry\VIEW).

But if you try to add a dynamic control (a dynamic menu, news-ticker, overviews…) on a master page you have a problem: A master page has no real controller itself (maybe a master page could have a controller – but for this problem there is a very easy way to do this).

The CTP 2 includes a special controller – the "ComponentController":

I use the "ComponentController" in my demo app to display the whole category list and the tagcloud.

My "EntrySideBarController" inherit from "ComponentController"

    public class EntrySidebarController : ComponentController
    {
        public void CategoryList()
        {
            ... viewdata = ...
            RenderView("CategoryList", viewData);
        }

        public void TagCloud()
        {
            ... viewdata = ...
            RenderView("TagCloud", viewData);
        }
    }

The views "CategoryList" & "TagCloud" are located in a special folder (root\Components\CONTROLLERNAME\Views\VIEWNAME):

image 

To render these components just use the "Html.RenderComponent" method (is similar to a usercontrol) :

    <%=Html.RenderComponent<EntrySidebarController>(component => component.CategoryList())%>
    <%=Html.RenderComponent<EntrySidebarController>(component => component.TagCloud())%>

Result:

image 

For more information about the ComponentController, look at this post:

Using the ComponentController in ASP.NET MVC CTP 2

kick it on DotNetKicks.com

2 Comments so far »

  1. Harry said

    am November 5 2008 @ 7:55 am

    RenderComponent seems gone in MVC Beta. Which method has been created to do the same?

  2. Robert Muehsig said

    am November 8 2008 @ 3:28 pm

    The RenderComponent (or how it´s named in the actual version of ASP.NET MVC) is gone to the ASP.NET MVC Future – just link the future DLL.

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: