What is the use of ChildActionOnly attribute in ASP .Net MVC C#?


Child Action is only accessible by a child request. It will not respond to the URL requests. If an attempt is made, a runtime error will be thrown stating - 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.

Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked using Action() or RenderAction() helpers.

Below is the Child Action Error when we try to invoke it using URL.

Controller

Example

using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ActionResult Index(){
         return View();
      }
      [ChildActionOnly]
      public ActionResult Countries(List<string> countries){
         return View(countries);
      }
   }
}

Index View

@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
@Html.Action("Countries", new { countries = new List<string>() { "USA", "UK",
"India", "Australia" } })

Countries View

@model List<string>
@foreach (string country in Model){
   <ul>
      <li>
         <b>
            @country
         </b>
      </li>
   </ul>
}

Output

Child actions can also be invoked using "RenderAction()" HTML helper as shown below.

@{
   Html.RenderAction("Countries", new { countryData = new List<string>() {
   "USA", "UK", "India", "Australia" } });
}

Updated on: 24-Sep-2020

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements