How to pass value from partial view to parent view in asp net mvc3
asp.net-mvc-3, partial-views
Solution
For access the data from TestPage in Header_PartialView you need to pass it as a parameter in `Html.RenderAction()` on `Main_LayoutPage.cshtml` like this:
@{ var test = ViewBag.testData1; }
@{Html.RenderAction("Header_PartialView", "Home", new { test = test });}
And in `Header_PartialView` action add parameter `string test` and pass it like as a model because ViewBag from layout doesn't comes here.
public ActionResult Header_PartialView(string test)
{
return View(model: test);
}
Then on `Header_PartialView.cshtml` you are getting the code:
@model string
@{
Layout = null;
}
<div>@Model</div>
Problem
I have one master page in which 3 partial view renders and it contains one render body (content place holder) for views. I am trying to pass data (any string) from my child view to one of the partial view rendered on master page. And for this I am using `Viewbag` but its not accessble on parent view. My Code is below : My Master page: [ `Main_Layout.chtml` ] ``` <body> <div> @{Html.RenderAction("Header_PartialView", "Home");} </div> <div> <table cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td id="tdLeft" class="lftPanel_Con"> <div> @{Html.RenderAction("LeftPanel_PartialView", "Home");} </div> </td> <td id="tdRight" width="100%"> <div> @RenderBody() </div> </td> </tr> </table> </div> <!--start footer--> <div> @{Html.RenderAction("Footer_PartialView", "Home");} </div> </body> ``` My Child View : [ `TestPage1.chtml` ] ``` @{ ViewBag.Title = "TestPage1"; Layout = "~/Views/Shared/Main_LayoutPage.cshtml"; var test1 = ViewBag.testData1; var test2 = ViewData["testData2"]; } <h2>TestPage1</h2> <div>This is only for testing</div> ``` My Controller Code : ``` public ViewResult TestPage1() { ViewBag.testData1 = "My first view bag data"; ViewData["testData2"] = "My second view data"; return View(); } ``` Now I want to access data of my TestPage on `Header_PartialView` views. ``` @{ var test = ViewBag.testData1; var test2 = ViewData["testData2"]; } ```