ASP.NET MVC CTP 2 shipped with a new controller class which you may have missed. Community feedback begged for a better way to handle component pages that don’t rely on the main page’s view data. A classic example might be a stock ticker. We would want a reusable component that you can place in other pages.
The ComponentController allows you to call a controller action from within the page itself. It’s use is very similar to the regular controller. You basically create a new class the inherits ComponentController. Then you create public methods as the actions of the controller. Within the action method, you can implement whatever logic you need the component to perform. You finally call RenderView to render the view just like the regular controllers.
It’s important to note that the ComponentController doesn’t look in the same places as the regular controller when finding the views. On this CTP, all component views need to reside in the right directory for the RenderView method to find it. The convention is Components/[ComponentControllerName]/Views/[ViewName] directory. In this case, the name of my controller is MyComponentController and the view name is CustomerOrderView
I’m not a big fan of forcing convention this since I may want to put my components wherever I please, but I digress. Let’s look at the controller.
This very simple controller has a single action named ShowCustomerOrders. This method calls my order repository and returns a list of orders for a customer. I will be able to use this on any view where I need a quick summary of the customer orders. It accepts a CustomerID and renders a view named CustomerOrderView.
From within the page, I’m using the lambda notion to make the call to this controller. The Html helper has a method called “RenderComponent“. I specify my component controller and the action it should call. In this case we are passing the customer ID “1″. This can be easily replaced with some of the view’s ViewData properties.
Taking a look at the view that my component will render, we see it is a simple list using a strongly-typed CustomerOrder as the ViewData.
That’s all there is to it. When we run the page, our customer orders show up where I placed the call to the RenderComponent method.
Hope this helps!
UPDATE: I uploaded the source code for the example. Download it here.