Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active January 13, 2022 09:49
Show Gist options
  • Save primaryobjects/8442193 to your computer and use it in GitHub Desktop.
Save primaryobjects/8442193 to your computer and use it in GitHub Desktop.
MVC C# .NET: Passing data from a child partial view to the parent page via ViewContext.ViewBag. This example demonstrates how to set the page title from a child partial view.
// In your HTML helper class, include this function:
/// <summary>
/// Returns the ViewBag of the parent page. Allows a child view to access the parent view's ViewBag object. A child view may then set a property accessible by the parent page.
/// </summary>
/// <returns>ViewBag</returns>
public static dynamic GetPageViewBag(this HtmlHelper html)
{
if (html == null || html.ViewContext == null) //this means that the page is root or parial view
{
return html.ViewBag;
}
ControllerBase controller = html.ViewContext.Controller;
while (controller.ControllerContext.IsChildAction) //traverse hierachy to get root controller
{
controller = controller.ControllerContext.ParentActionViewContext.Controller;
}
return controller.ViewBag;
}
// In your child partial view (ChildView.cshtml), include the following to set the shared data:
@using Web.Helpers
@{Html.GetPageViewBag().PageTitle = "My Custom Property Readable By Parent View"; }
// In your parent view (Page.cshtml), you can access the shared data simply by calling ViewContext.ViewBag:
@{ ViewBag.Title = ViewContext.ViewBag.PageTitle }
// (or for some error-checking and a default value, you can use this code:)
@{ ViewBag.Title = !string.IsNullOrEmpty(ViewContext.ViewBag.PageTitle) ? ViewContext.ViewBag.PageTitle : "Default Title"; }
@arulprabakaran
Copy link

Thanks @primaryobjects. It worked for me 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment