【问题标题】:Partial parameters using both ViewData Dictionary and the ViewBag deletes ViewBag data使用 ViewData Dictionary 和 ViewBag 的部分参数删除 ViewBag 数据
【发布时间】:2015-03-31 12:03:26
【问题描述】:

我需要将一些信息传递给部分 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 也不包含任何数据。这怎么可能?知道如何更好地处理这个问题吗?

【问题讨论】:

  • “已经在 ViewBag 中”是什么意思? ViewBag 仅在一个请求的生命周期内保留。你不能在 ViewBag 中放一些东西,提出一个请求,然后期望它在下一个请求中出现。
  • ViewBag 填充在 Controller 上。我添加了具体的代码来澄清。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 好的。由于没有人发布实际答案,我如何让其他观众知道他们可以在这篇文章中找到解决方案?

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


【解决方案1】:

看到这个帖子What's the difference between ViewData and ViewBag?

看起来“内部 ViewBag 属性在 ViewData 字典中存储为名称/值对”。这表明您在传递新的ViewDataDictionary 对象时覆盖了ViewBag

取自this blog post

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

【讨论】:

    猜你喜欢
    • 2011-12-21
    • 1970-01-01
    • 2011-06-09
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2013-05-28
    • 2018-01-08
    相关资源
    最近更新 更多