使用 ViewData Dictionary 和 ViewBag 的部分参数删除 ViewBag 数据

Partial parameters using both ViewData Dictionary and the ViewBag deletes ViewBag data

我需要将一些信息传递给部分 cshtml 视图。我为此使用 ViewDataDictionaryViewBag

public ActionResult TaskPage(int ID = 0)
{
    ViewBag.breadcrumbs = new string[] {
        "List", "Tasks"
    };
    ViewBag.title = "Editing - My selected itemd";
    ViewBag.id = ID;
    return View();
}

然后在组装视图时我也传递了一个 ViewDataDictionary

@Html.Partial("~/Views/Components/_Header.cshtml", new ViewDataDictionary { { "role", "task-page" } })

我的 _Header.cshmtl 文件同时使用了这个词典和 ViewBag.

  ViewBag.breadcrumbs = ViewBag.breadcrumbs != null ? ViewBag.breadcrumbs : new string[] { };
  var role = ViewData["role"];

令我惊讶的是,当我也通过 ViewDataDictionary 时,ViewBag 不包含任何数据。这怎么可能?知道如何更好地处理这个问题吗?

看到这个postWhat's the difference between ViewData and ViewBag?

看起来 "Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary." 表明您在传递新的 ViewDataDictionary 对象时覆盖了 ViewBag

取自this blog post

public dynamic ViewBag 
{ 
    get 
    { 
         if (_dynamicViewData == null) 
        {
            _dynamicViewData = 
            new DynamicViewDataDictionary(() => ViewData); 
        }
        return _dynamicViewData;
    }
}