Click here to Skip to main content
15,888,802 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How do you pass a parent ID to a child controller? Do I do this with Viewbag or is there another way. There is a link on the Index view for each row which should open the child view Index through the controller. How should this be done?

Parent Index View has a link:

@Html.ActionLink("Tensile", "Index","ToleranceTensile", new { id=item.ToleranceID }, null)


How should the controller on the child display the Index view for thAt parent ID?


public ActionResult Index(int id)
       {
           ViewBag.ToleranceHeaderID = id;
           return View(toleranceTensileRepository.GetToleranceTensilesByHeaderID(id));
       }

As well how can that value be passed to create view for child so any new records are added as children to the parent which was originally passed to child Index?
Posted
Updated 15-Jan-13 6:14am
v2

The last sentence is the key. But it is called more master-detail than parent-child...
So you want to select a "master" entity and than use that entity in several following detail action calls.
ViewBag is for passing non-model data from controller to the view, so that's not it.
You have several options:
1) cookie: on after master selection you send a cookie with the result that contains the master id, and you look for it in in the following calls
2) hidden field: if you use forms, you can add a hidden field that stores the master entity id, and you can use it in the detail actions.
3) TempData: you can pass data between calls but only for one hop, so if the user is jumping around the site, it won't work.
4) session: this is it. On master entity selection you store the master entity (or it's id) in a session variable and you can use it in all subsequent calls, until session is abandoned, timed out, or you dispose the variable. Be aware, that in the controller constructor the session is not yet constructed, so you can access it only in the actions.
 
Share this answer
 
Comments
Ryanm1324 15-Jan-13 15:42pm    
Thanks for your help. I got it to work using the hidden field approach.
Hi,
and even more simply just use your actionlink like below

C#
<%:Html.ActionLink("Text To display", "Index", new {  }, new { href = "/Parent/Child/" })%>


or you can add a javascript function to call your action like:
C#
<%:Html.ActionLink("Text To display", "Index", new { id = 3 }, new {  onclick = "return TestAction('CreatedOn');" })%>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900