Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Child Actions in ASP.NET MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2
    • 0
    • 778
    Comment on it

    Child Actions in ASP.NET MVC

    In ASP.NET MVC controller is defined as collection of action methods which are similar to function having public specifier.These actions can be called directly from browser by typing in URL request. But there are action methods referred as child action methods which cannot be called from a URL request but can be called from within a view of other action method.

     
    To make action method as child action method controller action is preceded with attribute [ChildActionOnly]. Now child action method can be called via following two html helpers in view.

     

    @Html.Action()
    
    @Html.RenderAction()
    

     

    Example to demonstrate Child Actions 

     

    • Declare a controller "Home" with action method Index and child action method "multiply"

     

    
       public class HomeController : Controller
        {
    	    //Action whose view will call child action "multiply"
            public ActionResult Index()
            {
                return View();
            }
    
    		//Child action method preceded with attribute ChildActionOnly
            [ChildActionOnly]
            public ActionResult multiply(List<int> list)
            {
                int product = 1;
                foreach (var i in list)
                {
                    product = product * i;
                }
                return Content("The product of numbers is:" + product);
            }
        }

     

        

    • Child Action Method cannot be accessed directly via URL request. If accessed gives following error

     

    • The Index view page

     

    <table>
        <tr>
            <td>
                @{
                    List<int> list = new List<int>() { 10, 20, 30 };
                }
                @Html.Action("multiply",new {list = list })
            </td>
        </tr>
    </table>

     

    Child Action called via @Html.Action by index view rendered through index action. It gives following output

     

     

    Child Actions in ASP.NET MVC

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: