Tuesday, May 26, 2015

Child Actions in ASP.NET MVC


Child Actions are the action methods which can be invoked within the view. This is used to work with the data in the view, which are not related to the main action method. For example, if you want to create a data driven widget in the view using data that is not related to the main action method, you will need to use the child action method.
In ASP.NET MVC any action can be used as a child action. However, to use an action only as a child action and attribute it with the ChildActionOnly. It will make sure the action is not called by any user request and will only be used in the view. A child action can be created as shown below:
This child action returns a partial view with the current time as the data in the partial view. The partial view is created as below:
CurrentTime.cshtml
In the main view, the child action can be used as shown below:
Above we are using child action from the same controller in which the main action is defined. To use child actions from a different controller, you have the option of passing the controller name as well. You can also pass input parameters to the child action. To demonstrate this, let us create the child action with an input parameter as follows:
In the view, a parameter can be passed to the child action as follow:
You may consider using the child action method in the following scenarios,
  • To use data in the view which is not related to the main controller
  • To create data driven widgets to be used on different views

No comments:

Post a Comment

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...