Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging the ViewBag inside a Controller that is NOT a child action, and retrieving it in the View context
    primarykey
    data
    text
    <p>Our application has a global Controller that all other Controllers inherit from; from within, in the <code>OnResultExecuting</code> override, I access an item (something obtained by accessing the Session, the <code>HttpContext</code> and the Web.config) that I store in the</p> <p><em>filterContext.ParentActionViewContext.ViewBag</em></p> <p>and this allows me to access this item in the ViewBag later in the lifecycle of the request.</p> <p><strong>PROBLEM</strong>: some of those filterContext are NOT child Action, and as such their <em>ParentActionViewContext</em> field is null, and I don't know of any other way to access the ViewBag.</p> <p><strong>QUESTION</strong>: if my controller stumbles upon a non-child Action, how can I still pass this item to the ViewBag?</p> <p>I would like to stress my inexperience with ASP.Net MVC4 - if there is a better way to approach this same problem, please do not hesitate to suggest it.</p> <p>EDIT: adding some code for clarification.</p> <p>This is where I save <strong>myItem</strong> in the ViewBag in my Controller method:</p> <pre><code>protected override void OnResultExecuting(ResultExecutingContext filterContext) { [...] if (filterContext.ParentActionViewContext != null &amp;&amp; filterContext.ParentActionViewContext.ViewBag != null) { filterContext.ParentActionViewContext.ViewBag["DealerId"] = myItem; } [...] base.OnResultExecuting(filterContext); } </code></pre> <p>And this is where I retrieve it inside my HtmlHelper:</p> <pre><code>public static MvcHtmlString DealerSpecificLessStyleSheet(this HtmlHelper htmlHelper) { var linkBuilder = new TagBuilder("link"); var dealerReferenceGuid = (string)htmlHelper.ViewBag["DealerId"]; /* Do something with this ID */ [...] return new MvcHtmlString(linkBuilder.ToString()); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload