Last active
January 13, 2022 09:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"; } | |
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
A big thanks from DotNek team.
It was really helpful and completely worked for us.
Thanks @primaryobjects. It worked for me 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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; ?