15 April 2008 ASP.NET MVC, Components Robert Muehsig

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


Written by Robert Muehsig

Software Developer - from Saxony, Germany - working on primedocs.io. Microsoft MVP & Web Geek.
Other Projects: KnowYourStack.com | ExpensiveMeeting | EinKofferVollerReisen.de