我需要将一些信息传递给部分cshtml视图。我使用了ViewDataDictionary
和ViewBag
。
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
不包含任何数据。怎么可能?知道如何更好地处理这个问题吗?
答案 0 :(得分:2)
请参阅此帖子What's the difference between ViewData and ViewBag?
看起来“内部ViewBag属性存储为ViewData字典中的名称/值对。”这表示当您传递新的ViewBag
对象
ViewDataDictionary
public dynamic ViewBag
{
get
{
if (_dynamicViewData == null)
{
_dynamicViewData =
new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewData;
}
}