【问题标题】:How to pass thw Viewdata to all the views in my controller?如何将 Viewdata 传递给我的控制器中的所有视图?
【发布时间】:2009-09-01 05:01:30
【问题描述】:

我有一个选择值的下拉列表

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Screenname(FormCollection collection)
    {
        Viewdata["screenname"] = collection[0];

        return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
    }

然后我想在其他类似的操作中访问这个 ViewData

   [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection, string screenname)
    {
        try
        {
            /// thats my dataobject which creates 

            DataObj.SaveData(Guid.Empty, collection, screenname);

            return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
        }
        catch
        {
            return View("Error");
        }
    }

索引看起来像这样......

    public ActionResult Index(string ScreenName)
    {
        ///thats my list 
        GetTable = new GetDataTable(ScreenName);

        return View(GetTable);
    }

首先,当我选择值并且索引正确执行时......但是当我再次尝试访问视图数据时,它不包含该值,所以任何人都可以提供帮助...... 或替代方法来保存和检索数据。

【问题讨论】:

  • 不要使用当前接受的答案(静态变量传递)。

标签: asp.net-mvc


【解决方案1】:

ViewData 对象特定于正在执行的特定操作。要在操作之间传递数据,请使用TempData。更多关于 MSDN 上的the difference between the two

您也可以通过Controller.Session 属性直接写入会话状态。

【讨论】:

    【解决方案2】:

    这实际上已经在这里经常被提及。目前的解决方案是在使用 RedirectToAction() 之前使用 TempData 保存您需要的数据。

    如果您搜索“RedirectToAction”,您会发现很多关于此主题的帖子,such as this one

    框架的下一个正式版本将解决这个问题。

    【讨论】:

    • 即使当我使用临时数据时,我也无法访问数据。它仍然是 null 。我已经尝试过...任何其他选项
    • 另外我还有一些操作要传递数据,所以请大家帮忙
    【解决方案3】:

    我使用视图从用户那里获取数据,然后将其保存到静态变量中,然后使用该变量将数据传递给所有其他视图。

    还是谢谢

    【讨论】:

    • 糟糕!!!解决方案。每个用户都将获得相同的静态变量集,如果另一个用户在第二个用户的重定向之间访问该页面,那么第二个用户将获得第一个用户的值。不要使用这个任何人。
    猜你喜欢
    • 1970-01-01
    • 2014-11-09
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多