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:
|
[ChildActionOnly]
public ActionResult CurrentTime()
{
return PartialView(DateTime.Now);
}
|
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
|
@model DateTime
<p>Current time : @Model.ToShortTimeString() </p>
|
In the main view, the child action can be used as shown below:
|
@Html.Action("CurrentTime");
|
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:
|
[ChildActionOnly]
public ActionResult CurrentTime(object name)
{
return PartialView(name);
}
|
In the view, a parameter can be passed to the child action as follow:
|
@Html.Action("CurrentTime", new { name = "Steve" });
|
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