简体   繁体   English

更改不是子动作的Controller内的ViewBag,并在View上下文中检索它

[英]Changing the ViewBag inside a Controller that is NOT a child action, and retrieving it in the View context

Our application has a global Controller that all other Controllers inherit from; 我们的应用程序具有一个全局控制器,所有其他控制器都继承自该控制器。 from within, in the OnResultExecuting override, I access an item (something obtained by accessing the Session, the HttpContext and the Web.config) that I store in the 从内部,在OnResultExecuting覆盖中,我访问存储在目录中的一项(通过访问Session, HttpContext和Web.config获得的项)

filterContext.ParentActionViewContext.ViewBag filterContext.ParentActionViewContext.ViewBag

and this allows me to access this item in the ViewBag later in the lifecycle of the request. 这样,稍后我就可以在请求的生命周期中在ViewBag中访问此项目。

PROBLEM : some of those filterContext are NOT child Action, and as such their ParentActionViewContext field is null, and I don't know of any other way to access the ViewBag. 问题 :其中一些filterContext不是子操作,因此,它们的ParentActionViewContext字段为null,而且我不知道其他任何方式来访问ViewBag。

QUESTION : if my controller stumbles upon a non-child Action, how can I still pass this item to the ViewBag? 问题 :如果我的控制器偶然发现一个非子级Action,我如何仍将这个项目传递给ViewBag?

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. 我想强调一下我对ASP.Net MVC4的经验-如果有更好的方法来解决同一问题,请不要犹豫地提出建议。

EDIT: adding some code for clarification. 编辑:添加一些代码进行澄清。

This is where I save myItem in the ViewBag in my Controller method: 这是我在Controller方法中将myItem保存在ViewBag中的位置:

protected override void OnResultExecuting(ResultExecutingContext filterContext) {

    [...]

    if (filterContext.ParentActionViewContext != null && filterContext.ParentActionViewContext.ViewBag != null) {
        filterContext.ParentActionViewContext.ViewBag["DealerId"] = myItem;
    }

    [...]

    base.OnResultExecuting(filterContext);
}

And this is where I retrieve it inside my HtmlHelper: 这是我在HtmlHelper中检索它的地方:

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());
    }

I access an item (something obtained by accessing the Session... 我访问一个项目(通过访问Session获得的东西...

If you already have the value in Session then you don't need to have it in the ViewBag just specifically in your current situation. 如果您已经在Session中拥有该值,那么就不必专门在当前情况下在ViewBag中拥有它。 You can use a helper class to get it to your views: 您可以使用帮助器类将其显示在视图中:

public sealed class UIHelper
{
    public static string GetThatValue()
    {
        return (string)HttpContext.Current.Session["target_key"];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM