Child Actions in ASP.NET MVC
In ASP.NET MVC controller is defined as collection of action methods which are similar to function having public specifier.These actions can be called directly from browser by typing in URL request. But there are action methods referred as child action methods which cannot be called from a URL request but can be called from within a view of other action method.
To make action method as child action method controller action is preceded with attribute [ChildActionOnly]. Now child action method can be called via following two html helpers in view.
@Html.Action()
@Html.RenderAction()
Example to demonstrate Child Actions
- Declare a controller "Home" with action method Index and child action method "multiply"
public class HomeController : Controller
{
//Action whose view will call child action "multiply"
public ActionResult Index()
{
return View();
}
//Child action method preceded with attribute ChildActionOnly
[ChildActionOnly]
public ActionResult multiply(List<int> list)
{
int product = 1;
foreach (var i in list)
{
product = product * i;
}
return Content("The product of numbers is:" + product);
}
}
- Child Action Method cannot be accessed directly via URL request. If accessed gives following error
<table>
<tr>
<td>
@{
List<int> list = new List<int>() { 10, 20, 30 };
}
@Html.Action("multiply",new {list = list })
</td>
</tr>
</table>
Child Action called via @Html.Action by index view rendered through index action. It gives following output
0 Comment(s)