簡體   English   中英

更改不是子動作的Controller內的ViewBag,並在View上下文中檢索它

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

我們的應用程序具有一個全局控制器,所有其他控制器都繼承自該控制器。 從內部,在OnResultExecuting覆蓋中,我訪問存儲在目錄中的一項(通過訪問Session, HttpContext和Web.config獲得的項)

filterContext.ParentActionViewContext.ViewBag

這樣,稍后我就可以在請求的生命周期中在ViewBag中訪問此項目。

問題 :其中一些filterContext不是子操作,因此,它們的ParentActionViewContext字段為null,而且我不知道其他任何方式來訪問ViewBag。

問題 :如果我的控制器偶然發現一個非子級Action,我如何仍將這個項目傳遞給ViewBag?

我想強調一下我對ASP.Net MVC4的經驗-如果有更好的方法來解決同一問題,請不要猶豫地提出建議。

編輯:添加一些代碼進行澄清。

這是我在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);
}

這是我在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());
    }

我訪問一個項目(通過訪問Session獲得的東西...

如果您已經在Session中擁有該值,那么就不必專門在當前情況下在ViewBag中擁有它。 您可以使用幫助器類將其顯示在視圖中:

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