Home > DeveloperSection > Beginner > Child Action Method in Asp.Net Mvc 4

Child Action Method in Asp.Net Mvc 4


ASP.NET MVC ASP.NET MVC 
Ratings:
4 Comment(s)
 6132  View(s)
Rate this:

Child Action Method in Asp.Net Mvc 4

In this article, I’m explaining the child action method in asp.net mvc 4 and its uses.

Introduction

Any public method in a controller class is an action method. Every action method in a controller class can be invoked via an URL from web browser or a view page in application.

A Child Action in ASP.Net MVC is kind of similar to that of a User Control in ASP.Net web forms. It allows for a controller to execute for a portion of the rendered area of a view, just like in Web Forms where you can execute a User Control for a portion of the rendered area of a page.

We can annotate an action method with [ChildActionOnly] attribute for creating a child action.

Example

Step 1

First create a basic asp.net mvc 4 application and a controller named “HomeController” to it:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace ChildActionMvcApp.Controllers

{

    public class HomeController : Controller

    {

       

 

        public ActionResult Index()

        {

            ViewBag.HomeAction = "Home Action Method Called";

            return View();

        }

 

        [ChildActionOnly]

        public ActionResult ChildAction()

        {

          

            return View();

        }

    }

}

 

Step 2

Now add two views named “Index” and “ChildAction” like this”

Index

@{

    ViewBag.Title = "Index";

}

 

<h2>Child Action Method Sample</h2>

 

<div>

    <div style="width:100%">

        @ViewBag.HomeAction

    </div>

    <div style="width:100%">

        @Html.ActionLink("Child Action Method""ChildAction""Home")

    </div>

   

 

    <div style="width:100%">

        @Html.Action("ChildAction")

    </div>

</div>

 

 

ChildAction

@{

    ViewBag.Title = "ChildAction";

}

 

<h2>Child Action Rendered</h2>

 

Output

Now run the application:

 

Child Action Method in Asp.Net Mvc 4

 

As you can see that the child action is rendered.

Now click on Child Action Method link:

Child Action Method in Asp.Net Mvc 4


Nice article

By Pravesh Singh on   2 years ago
Nice article

Good Article

By Chintoo Semi on   2 years ago
Good Article

Good Article for beginners

By Goti Bandu on   2 years ago
Good Article for beginners

Nice Article

By Chintoo Semi on   2 years ago
Good article for beginners

Don't want to miss updates? Please click the below button!

Follow MindStick