开发者

Using ASP.NET MVC SubControllers with action parameters?

开发者 https://www.devze.com 2022-12-12 02:17 出处:网络
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)

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 me开发者_开发技巧thod:

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消