views:

357

answers:

1

I am experimenting with MvcContrib subcontrollers. Looking at the example in the source, your parent controller (HomeController) takes an action which takes the subcontroller (FirstLevelSubController) as a parameter:

public class HomeController : Controller
{
    public ActionResult Index(FirstLevelSubController firstLevel)
    {
        ViewData["Title"] = "Home Page";
        return View();
    }
}

In Home's index view, you call ViewData.Get like this to render the subcontroller and it's view:

<div style="border:dotted 1px blue">
    <%=ViewData["text"] %>
    <% ViewData.Get<Action>("firstLevel").Invoke(); %>
</div>

The subcontroller's action gets called (ignore the secondlevelcontroller, the example is just demonstrating how you can nest multiple subcontrollers):

public class FirstLevelSubController : SubController
{
    public ViewResult FirstLevel(SecondLevelSubController secondLevel)
    {
        ViewData["text"] = "I am a first level controller";
        return View();
    }
}

This all works, the subcontroller's view gets rendered inside the parent view.

But what if I need other parameters in my home controller's action? For example, I may want to pass a Guid to my controller's index method:

public class HomeController : Controller
{
    public ActionResult Index(Guid someId, FirstLevelSubController firstLevel)
    {
        //Do something with someId
        ViewData["Title"] = "Home Page";
        return View();
    }
}

There doesn't seem to be any way to do <% ViewData.Get("firstLevel").Invoke(); %> with parameters. So I can't figure out how to link to my controller from another controller passing a parameter like this:

Html.ActionLink<HomeController>(x => x.Index(someThing.Id), "Edit")

Perhaps I am approaching this the wrong way? How else can I get my parent controller to use a subcontroller, but also do interesting stuff like accept parameters / arguments?

+2  A: 

Have a look at this blog post:

Passing objects to SubControllers
http://mhinze.com/passing-objects-to-subcontrollers/

Note that SubControllers are deprecated. They have been replaced with RenderAction.

Robert Harvey
Good spot - it looks like SubControllers are indeed deprecated - I tried RenderAction, and it just works beautifully first time :) Thanks, I would have spent days trying to get that to work!
James Allen