CHILD Action Methods in ASP.Net MVC 4

Introduction
 
In this article, we will explore Child Action methods accessible at the View level. In general, each public method in a controller class is an action method.
 
There could be multiple scenarios when we want to display some dynamic information (data) on pages. A Child action is helpful in those scenarios.
 
A ChildAction method is an action method thought its accessible from the View only, if you invoked this action via an URL then it prompts you an error that we will look down the level in this article.
 
 
 
I have a HomeController in the MVC application that contains code as given below:
  1. public class HomeController : Controller    
  2. {    
  3.     public ActionResult Index()    
  4.     {    
  5.         ViewBag.TempValue = "Index Action called at HomeController";    
  6.         return View();    
  7.     }    
  8.      
  9.     [ChildActionOnly]    
  10.     public ActionResult ChildAction(string param)    
  11.     {    
  12.         ViewBag.Message = "Child Action called. " + param;    
  13.         return View();    
  14.     }    
  15. }  
To behave an action as child action it requires decorating with [ChildActionOnly] as shown in the image below:
 
 
Initially it is invoking an Index action that in turn returns to Index views and at the View level it calls the ChildAction named “ChildAction”.
 
This is the code of index.cshtml:
  1. @{    
  2.     ViewBag.Title = "Index";       
  3. }       
  4. <h2>       
  5.     Index       
  6. </h2>      
  7.       
  8. <!DOCTYPE html>       
  9. <html>       
  10. <head>       
  11.     <title>Error</title>       
  12. </head>       
  13. <body>       
  14.     <ul>     
  15.         <li>       
  16.             @ViewBag.TempValue       
  17.         </li>       
  18.         <li>@ViewBag.OnExceptionError</li>       
  19.         @*<li>@{Html.RenderAction("ChildAction"new { param = "first" });}</li>@**@       
  20.         @Html.Action("ChildAction""Home"new { param = "first" })       
  21.     </ul>       
  22. </body>       
  23. </html>  
And this is how we declare an action in a view as depicted in the image below:
 
 
Now I run the application and it will call an action method via the Index.cshtml page. And the result is as below:
 
 
Note: if you try to access the ChildAction method directly than it prompts you with an error as per the image below.
 
Copy this URL and paste it into a browser: http://localhost:50255/Home/ChildAction/Second
 
It prompts you with the error:
 
 
It may help you sometime in the future.
 
Thanks
 
To understand more about MVC please go through the following link:
 
 
Enjoy coding and reading.