asp.net mvc 3 - How can I get my ViewContext.ViewBag to work with my code? -
i’m trying create htmlhelper allow me communicate across parent , child views. got tutorial here: https://gist.github.com/primaryobjects/8442193.
first created class , method this:
namespace schoolin.helpers { public static class viewbaghelpers { public static dynamic getpageviewbag(this htmlhelper html) { if (html == null || html.viewcontext == null) //this means page root or parial view { return html.viewdata; } controllerbase controller = html.viewcontext.controller; while (controller.controllercontext.ischildaction) //traverse hierachy root controller { controller = controller.controllercontext.parentactionviewcontext.controller; } return controller.viewbag; } } }
in child view add using statement:
@using schoolin.helpers
and
@{html.getpageviewbag().pagetitle = "my custom property readable parent view"; }
in parent view i’m trying this:
@{ viewbag.title = viewcontext.viewbag.pagetitle }
so guess have 2 problems. first don’t have access html.viewbag tutorial , in parent view can’t do...
viewcontex.viewbag.
any idea how can make work? help.
i managed working after couple of tweaks. make sure syntax correct , title set after partial rendered.
layout page (_layout.cshtml):
@using schoolin.helpers @* nb. example did not include call partial. *@ @html.partial("_child") @* following line must appear after partial rendered viewbag have been set. *@ @* nb. example missing semicolon. *@ @{ viewbag.title = viewcontext.viewbag.pagetitle; }
partial view (_child.cshtml):
@using schoolin.helpers @{html.getpageviewbag().pagetitle = "my custom property readable parent view"; }
Comments
Post a Comment