2013-07-15 57 views
2

我有一個母版頁,其中3個部分視圖呈現,並且它包含一個用於視圖的呈現正文(內容佔位符)。如何在asp net mvc3中將部分視圖的值傳遞給父視圖

我想從我的子視圖傳遞數據(任何字符串)到母版頁上呈現的部分視圖之一。對此,我使用Viewbag,但在父視圖上無法訪問。

我的代碼如下:

我的母版頁:[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> 

我的孩子查看:[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> 

我的控制器代碼:

public ViewResult TestPage1() 
     { 
      ViewBag.testData1 = "My first view bag data"; 
      ViewData["testData2"] = "My second view data"; 
      return View(); 
     } 

現在我想訪問我的TestPage的數據Header_PartialView的意見。

@{ 
    var test = ViewBag.testData1; 
    var test2 = ViewData["testData2"]; 
} 

回答

5

對於訪問從TestPage在Header_PartialView你需要的數據把它作爲在Html.RenderAction()參數上Main_LayoutPage.cshtml這樣的:

@{ var test = ViewBag.testData1; } 
@{Html.RenderAction("Header_PartialView", "Home", new { test = test });} 

並在Header_PartialView操作中添加參數string test並將其作爲模型傳遞,因爲佈局中的ViewBag不會將她即

public ActionResult Header_PartialView(string test) 
{ 
    return View(model: test); 
} 

然後在Header_PartialView.cshtml你所得到的代碼:

@model string 

@{ 
    Layout = null; 
} 
<div>@Model</div> 
1

嘗試像這樣在你的部分:

@{ 
    var test = ViewContext.ParentActionViewContext.ViewData["testData1"]; 
    var test2 = ViewContext.ParentActionViewContext.ViewData["testData2"]; 
} 
+0

'串T傳遞價值itlePrefix =(string)ViewContext.ParentActionViewContext.ViewData [「TitlePrefix」];' – ppumkin

1

我覺得這是更好地在這裏使用HttpContext.Items

@{ 
    this.ViewContext.HttpContext.Items["Stuff"] = "some-data"; 
} 

您可以在請求中呈現的每個視圖中訪問此數據。此數據對單個HTTP請求有效。

更多信息:

https://msdn.microsoft.com/en-us/library/system.web.httpcontext.items(v=vs.110).aspx

When can we use HttpContext.Current.Items to stores data in ASP.NET?

+0

在父視圖中你可以調用像ViewContext.HttpContext.Items [「stuff」] – Ashutosh

1

我可以簡單地使用

TempData["Msg"]="My Data";

,而不是ViewBag.Msg="My Data";

相關問題