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"; }
Copy link

ghost commented Jan 10, 2018

html == null why it would be necessary? Can HtmlHelper be null? And on top of that if it is null this would crash return html.ViewBag; ?

@mrnams
Copy link

mrnams commented Oct 9, 2018

Hello experts,I want to implement load more button for my website ,https://mrnams.com

Can any one please give idea how to implement load more button to load more videos without refreshing (I mean without loosing loaded videos) page.

Similar to youtube functionality.

I am using .net core 2.1 version

@NeshatKh
Copy link

NeshatKh commented Nov 2, 2020

A big thanks from DotNek team.
It was really helpful and completely worked for us.

@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