X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Friday, October 23, 2015

Child action only in MVC


Introduction

The public methods in the controller class can be called as action. So the actions can be invoked through the URL. But the child actions cannot be directly accessed through the URL instead it will be called from the view.


How to Use

Suppose we have to display the same information across couple of pages /views then we can create a partial view and this partial view can be used in those views.

Child Actions cannot be accessed through the URL. It should be called from the parent view. From the parent view we can use -

@Html.Action("ChildActionMethod", "ControllerName")

Or we can call the child action methods like this -

@{ Html.RenderAction("ChildActionMethod", "ControllerName"); }

And my child action methods should be decorated with the attribute - "ChildActionOnly" - which signifies the action can be called only as a child.

Below is my sample child action method -

[ChildActionOnly]
public ActionResult ChildActionMethod()
{
    return PartialView();
}

So as mentioned above, this child action can be called from -

@Html.Action -> Returns the action result as HTML String.  

@Html.RenderAction -> Renders the action result directly into the view.  

And as you can observe my child action is returning the partial view. Its not mandatory for child action to return the partial view always but its a good practice to return the partial view over view.

If you are accessing the child action method through URL you will get a error like -



Hope it helps. Please comment your thoughts below.





No comments:

Post a Comment

Comments Section