
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use of ChildActionOnly Attribute in ASP.NET MVC
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" } }); }
Advertisements