Introduction
The action method which is decorated with the ChildActionOnly attribute is called Child Action in MVC. Child Action is only accessible by a child request. It will not respond to the URL requests. Let's understand the use of a ChildActionOnly attribute in our application.
Step 1
Step 2
Step 3
Step 4
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with a default controller. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of "default", just write "Home".

The complete code for Home Controller
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace ChildActionAttribute_Demo.Controllers
- {
- public class HomeController : Controller
- {
- // GET: Home
- public ActionResult Index()
- {
- return View();
- }
- [ChildActionOnly]
- public ActionResult Students(List<string>studentList)
- {
- return View(studentList);
- }
- }
- }
Step 5
Index View
- @model List<string>
- @{
- ViewBag.Title = "Index";
- }
- <h2>List of students</h2>
- @Html.Action("Students", new { studentList = new List<string>() { "Farhan Ahmed", "Irfan Ahmed", "Irshad Ahmed" } })
- @model List<string>
- @{
- Layout = null;
- }
- @foreach (var stud in Model)
- {
- <ul>
- <li>
- @stud
- </li>
- </ul>
- }
Points to remember about ChildActionOnly attribute
- The action method which is decorated with the ChildActionOnly attribute is called a child action method.
- Child action methods do not respond to URL requests. If an attempt is made, a runtime error is thrown stating that Child action is accessible only by a child request.
- Child action methods can be invoked by making child request from a view using Action() and RenderAction() HTML helpers.
- An action method doesn’t need to have [ChildActionOnly] attribute to be used as a child action but uses this attribute to prevent if you want to prevent the action method from being invoked as a result of a user request.
- Child actions are typically associated with partial views, although this is not compulsory.
- Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked using Action() or RenderAction() helpers.
- Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods. We will cover this when we discuss the [OutputCache] attribute.
Step 6
http://localhost:59591/Home/Index



Join the conversation! Your thoughts help the community grow.