Shravan Kumar Kasagoni

Skip Navigation
Child Action Methods in ASP.NET MVC

Child Action Methods in ASP.NET MVC

 /  Leave a response

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.

My scenario is some dynamic information (data) need to displayed on couple pages in my application. Generally we end up in adding that data to model passed to views by action methods. We duplicate same data in multiple models where we brake DRY (Don’t Repeat Yourself) principle.

To handle this scenario ASP.NET MVC provides child action methods. Any action method can be child an action method but child actions are action methods invoked from within a view, you can not invoke child action method via user request (URL).

We can annotate an action method with [ChildActionOnly] attribute for creating a child action. Normally we use child action methods with partial views, but not every time.

[ChildActionOnly] represents an attribute that is used to indicate that an action method should be called only as a child action.

In my application couple of pages need to display a news widget, but news will be dynamic based on page category.

public ActionResult GetNews(string category)
    var newsProvider = new NewsProvider();
    var news = newsProvider.GetNews(category);
    return View(news);

Above child action method can be invoked  inside any view in the application using Html.RenderAction() or Html.Action() method.

@Html.Action("GetNews", "Home", new { category = "Sports"})


@{ Html.RenderAction("GetNews", "Home", new { category = "finance"}); }

Child action methods help us in avoid duplicating data in multiple places. You can read more about Action() and RenderAction()  at following link

Write a response

Your email address will not be published.

All code will be displayed literally.