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

时间:2015-03-31 12:03:27

标签: c# razor asp.net-mvc-partialview viewbag viewdata

我需要将一些信息传递给部分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"];

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

1 个答案:

答案 0 :(得分:2)

请参阅此帖子What's the difference between ViewData and ViewBag?

看起来“内部ViewBag属性存储为ViewData字典中的名称/值对。”这表示当您传递新的ViewBag对象

时,您将覆盖ViewDataDictionary

取自this blog post

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