2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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!
@AbhishekMehta: This Wayback Machine link should suffice for now. Also note the last paragraph in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.