58

I read about child actions in MVC (fundamental book), but I don't really know what it is?

Could some one please explain these methods?

Liam
  • 27,717
  • 28
  • 128
  • 190
Shahrooz Jafari
  • 925
  • 3
  • 9
  • 16

3 Answers3

97

Phil Haack explains it nicely in this blog post. Basically a child action is a controller action that you could invoke from the view using the Html.Action helper:

@Html.Action("SomeActionName", "SomeController")

This action will then execute and render its output at the specified location in the view. The difference with a Partial is that a partial only includes the specified markup, there's no other action executing than the main action.

So you basically have the main action which received the request and rendered a view, but from within this view you could render multiple child actions which will go through their independent MVC lifecycle and eventually render the output. And all this will happen in the context of a single HTTP request.

Child actions are useful for creating entire reusable widgets which could be embedded into your views and which go through their independent MVC lifecycle.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • can call non-child action frim view? – Shahrooz Jafari Sep 21 '12 at 13:51
  • 10
    Actually when you call `Html.Partial` the action is automatically a child action. If you decorate the action with the `[ChildActionOnly]` attribute then you could use it only as a child action - you cannot access it directly. – Darin Dimitrov Sep 21 '12 at 15:16
  • I think one difference is action method can call from any view?right? – Shahrooz Jafari Sep 21 '12 at 16:44
  • 2
    Yes, but only from views. You could also type the url in your browser address bar and you will invoke a standard controller action. – Darin Dimitrov Sep 21 '12 at 16:45
  • 1
    @DarinDimitrov That's the answer I was looking for! There's no real difference between a regular "action" and a "child action". I was thinking the attribute was a requirement, but it appears to be more of a security feature so that an action that will only ever be used to render a partial, is not able to be accessed publicly from a browser directly. – ProxyTech Jan 15 '15 at 01:23
7

A child action is an action that is invoked by using html.renderaction or html.action helper from inside of a view.

Kumar Manish
  • 3,746
  • 3
  • 37
  • 42
2

A child action is an action method that is invoked in the view through @Html.Action().

Example I have an Action on my controller.

public DateTime Time(DateTime time)
{
    return time;
}

To call this action from the View i will use:

@Html.Action("Time", new { time = DateTime.Now }) 
yogihosting
  • 5,494
  • 8
  • 47
  • 80
  • Inadequate example, with no explanation: the child action entails some presentation logic to be reused, which in the example presented is better accomplished by display template. – timmi4sa Mar 11 '20 at 02:05