178

When would you use the attribute ChildActionOnly? What is a ChildAction and in what circumstance would you want restrict an action using this attribute?

6 Answers 6

169

The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. An action method doesn’t need to have this attribute to be used as a child action, but we tend to use this attribute to prevent the action methods from being invoked as a result of a user request. Having defined an action method, we need to create what will be rendered when the action is invoked. Child actions are typically associated with partial views, although this is not compulsory.

  1. [ChildActionOnly] allowing restricted access via code in View

  2. State Information implementation for specific page URL. Example: Payment Page URL (paying only once) razor syntax allows to call specific actions conditional

4
  • Example use in a view: <% Html.RenderAction("MyChildAction", "MyController"); %>. Thus you cannot call a child action with GET and routing May 29, 2013 at 10:35
  • 12
    Example code: @Clark-Kent // example from Music Store // GET: /ShoppingCart/CartSummary [ChildActionOnly] public ActionResult CartSummary() { // your stuff } /ShoppingCart/CartSummary will return "The action 'CartSummary' is accessible only by a child request." So you prevent a GET to a certain controller directly, but only from within another controller/action. Likely: _Partial views. Sep 26, 2013 at 12:19
  • 1
    How to best catch the InvalidOperationException when a Method marked <ChildActionOnly> is called via the browser? Feb 11, 2014 at 22:32
  • I had to use @Html.Action :)
    – chris c
    Feb 16, 2020 at 22:50
133

With [ChildActionOnly] attribute annotated, an action method can be called only as a child method from within a view. Here is an example for [ChildActionOnly]..

there are two action methods: Index() and MyDateTime() and corresponding Views: Index.cshtml and MyDateTime.cshtml. this is HomeController.cs

public class HomeController : Controller
 {
    public ActionResult Index()
    {
        ViewBag.Message = "This is from Index()";
        var model = DateTime.Now;
        return View(model);
    }

    [ChildActionOnly]
    public PartialViewResult MyDateTime()
    {
        ViewBag.Message = "This is from MyDateTime()";

        var model = DateTime.Now;
        return PartialView(model);
    } 
}

Here is the view for Index.cshtml.

@model DateTime
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
<div>
    This is the index view for Home : @Model.ToLongTimeString()
</div>
<div>
    @Html.Action("MyDateTime")  // Calling the partial view: MyDateTime().
</div>

<div>
    @ViewBag.Message
</div>

Here is MyDateTime.cshtml partial view.

@model DateTime

<p>
This is the child action result: @Model.ToLongTimeString()
<br />
@ViewBag.Message
</p>
 if you run the application and do this request http://localhost:57803/home/mydatetime
 The result will be Server Error like so: 

enter image description here

This means you can not directly call the partial view. but it can be called via Index() view as in the Index.cshtml

     @Html.Action("MyDateTime")  // Calling the partial view: MyDateTime().
 

If you remove [ChildActionOnly] and do the same request http://localhost:57803/home/mydatetime it allows you to get the mydatetime partial view result:
This is the child action result. 12:53:31 PM 
This is from MyDateTime()
2
  • i think this explanation was a "Full stop" , thanks men Apr 27, 2019 at 18:49
  • but it can be achieved using NonAction also, what difference does it make?
    – Imad
    Jul 12, 2019 at 5:02
75

You would use it if you are using RenderAction in any of your views, usually to render a partial view.

The reason for marking it with [ChildActionOnly] is that you need the controller method to be public so you can call it with RenderAction but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.

5
  • 2
    similar to [NonAction]. is it? what s the difference then?
    – DarthVader
    Oct 16, 2012 at 3:23
  • 10
    @DarthVader - Similar, but with [NonAction] you would not be able to call it using RenderAction either Oct 16, 2012 at 12:40
  • @EricPetroelje : What can be benefits of marking the Action Method as NonActionAttribute in real projects?
    – wuhcwdc
    Jun 16, 2013 at 17:39
  • 1
    @Pankaj - Honestly, I can't think of any really good reasons. If you don't want a method on a controller to be accessed via a URL, the best solution would just be to make the method private or protected. I can't really think of any good reason why you would want to make a controller method public except if you wanted to either be able to call it directly or via RenderAction Jun 17, 2013 at 13:18
  • @Eric: some times we need to write small code to calculate, so if that is public in controller then it can be accessed by the url, if you don't want it to be access by URL at all then mark it as [NonAction]
    – Ali Adravi
    Apr 30, 2014 at 18:06
11

FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here

10

A little late to the party, but...

The other answers do a good job of explaining what effect the [ChildActionOnly] attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render @Html.Partial("_MyParialView") directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.

This can come in handy, for example, in _Layout.cshtml. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render @Html.Action in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout page need not have a model. It follows that all other view models need not inherit from any base view model.

I'm sure there are other reasons to use the [ChildActionOnly] attribute, but this seems like a good one to me, so I thought I'd share.

1
  • 1
    Another advantage is, if a partial call is wrapped in an action call, then we can add a cache attribute to it.
    – kamgman
    Apr 16, 2019 at 3:24
-1
    public class HomeController : Controller  
    {  
        public ActionResult Index()  
        {  
            ViewBag.TempValue = "Index Action called at HomeController";  
            return View();  
        }  

        [ChildActionOnly]  
        public ActionResult ChildAction(string param)  
        {  
            ViewBag.Message = "Child Action called. " + param;  
            return View();  
        }  
    }  


The code is initially invoking an Index action that in turn returns two Index views and at the View level it calls the ChildAction named “ChildAction”.

    @{
        ViewBag.Title = "Index";    
    }    
    <h2>    
        Index    
    </h2>  

    <!DOCTYPE html>    
    <html>    
    <head>    
        <title>Error</title>    
    </head>    
    <body>    
        <ul>  
            <li>    
                @ViewBag.TempValue    
            </li>    
            <li>@ViewBag.OnExceptionError</li>    
            @*<li>@{Html.RenderAction("ChildAction", new { param = "first" });}</li>@**@    
            @Html.Action("ChildAction", "Home", new { param = "first" })    
        </ul>    
    </body>    
    </html>  


      Copy and paste the code to see the result .thanks 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.