ViewBag、ViewData 和 TempData [英] ViewBag, ViewData and TempData

查看:31
本文介绍了ViewBag、ViewData 和 TempData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下,什么时候用

  1. 临时数据
  2. 查看包
  3. 查看数据

我有一个要求,我需要在控制器一中设置一个值,该控制器将重定向到控制器二,控制器二将呈现视图.

我尝试使用 ViewBag,当我到达控制器 2 时该值丢失了.

我可以知道什么时候使用以及优点或缺点吗?

谢谢

解决方案

1)临时数据

允许您存储在重定向后仍然存在的数据.在内部,它使用 Session 作为后备存储,在进行重定向后,数据会自动驱逐.模式如下:

public ActionResult Foo(){//将一些内容存储到临时数据中,这些内容将在一次重定向期间可用TempData["foo"] = "bar";//如果将某些内容存储到 TempData 中,则应始终重定向//将消耗此数据的控制器操作return RedirectToAction("bar");}公共操作结果栏(){var foo = TempData["foo"];...}

<块引用>

2)ViewBag、ViewData

允许您将数据存储在将在相应视图中使用的控制器操作中.这假设该操作返回一个视图并且不重定向.仅在当前请求期间存活.

模式如下:

public ActionResult Foo(){ViewBag.Foo = "bar";返回视图();}

并在视图中:

@ViewBag.Foo

或使用 ViewData:

public ActionResult Foo(){ViewData["Foo"] = "bar";返回视图();}

并在视图中:

@ViewData["Foo"]

ViewBag 只是 ViewData 的动态包装器,仅存在于 ASP.NET MVC 3 中.

话虽如此,这两种构造都不应该被使用.您应该使用视图模型和强类型视图.所以正确的模式如下:

查看模型:

公共类 MyViewModel{公共字符串 Foo { 获取;放;}}

操作:

public Action Foo(){var model = new MyViewModel { Foo = "bar" };返回视图(模型);}

强类型视图:

@model MyViewModel@Model.Foo

<小时>

在这个简短的介绍之后,让我们回答您的问题:

<块引用>

我的要求是我想在控制器中设置一个值,即控制器将重定向到 ControllerTwo 和 Controller2 将呈现视图.

公共类 OneController:控制器{公共 ActionResult 索引(){TempData["foo"] = "bar";return RedirectToAction("index", "二");}}公共类 TwoController:控制器{公共 ActionResult 索引(){var 模型 = 新的 MyViewModel{Foo = TempData["foo"] 作为字符串};返回视图(模型);}}

和对应的视图(~/Views/Two/Index.cshtml):

@model MyViewModel@Html.DisplayFor(x => x.Foo)

<小时>

使用 TempData 也有缺点:如果用户在目标页面上按 F5,数据将会丢失.

我个人也不使用 TempData.这是因为它在内部使用 Session 而我在我的应用程序中禁用了 session.我更喜欢一种更 RESTful 的方式来实现这一点.即:在执行重定向的第一个控制器操作中,将对象存储在您的数据存储中,并在重定向时使用生成的唯一 ID.然后在目标操作上使用此 id 取回最初存储的对象:

公共类 OneController:控制器{公共 ActionResult 索引(){var id = Repository.SaveData("foo");return RedirectToAction("index", "two", new { id = id });}}公共类 TwoController:控制器{公共 ActionResult 索引(字符串 id){var 模型 = 新的 MyViewModel{Foo = Repository.GetData(id)};返回视图(模型);}}

视图保持不变.

Could any body explain, when to use

  1. TempData
  2. ViewBag
  3. ViewData

I have a requirement, where I need to set a value in a controller one, that controller will redirect to Controller Two and Controller Two will render the View.

I have tried to use ViewBag, the value gets lost by the time I reach Controller Two.

Can I know when to use and advantages or disadvantages?

Thanks

解决方案

1)TempData

Allows you to store data that will survive for a redirect. Internally it uses the Session as backing store, after the redirect is made the data is automatically evicted. The pattern is the following:

public ActionResult Foo()
{
    // store something into the tempdata that will be available during a single redirect
    TempData["foo"] = "bar";

    // you should always redirect if you store something into TempData to
    // a controller action that will consume this data
    return RedirectToAction("bar");
}

public ActionResult Bar()
{
    var foo = TempData["foo"];
    ...
}

2)ViewBag, ViewData

Allows you to store data in a controller action that will be used in the corresponding view. This assumes that the action returns a view and doesn't redirect. Lives only during the current request.

The pattern is the following:

public ActionResult Foo()
{
    ViewBag.Foo = "bar";
    return View();
}

and in the view:

@ViewBag.Foo

or with ViewData:

public ActionResult Foo()
{
    ViewData["Foo"] = "bar";
    return View();
}

and in the view:

@ViewData["Foo"]

ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3.

This being said, none of those two constructs should ever be used. You should use view models and strongly typed views. So the correct pattern is the following:

View model:

public class MyViewModel
{
    public string Foo { get; set; }
}

Action:

public Action Foo()
{
    var model = new MyViewModel { Foo = "bar" };
    return View(model);
}

Strongly typed view:

@model MyViewModel
@Model.Foo


After this brief introduction let's answer your question:

My requirement is I want to set a value in a controller one, that controller will redirect to ControllerTwo and Controller2 will render the View.

public class OneController: Controller
{
    public ActionResult Index()
    {
        TempData["foo"] = "bar";
        return RedirectToAction("index", "two");
    }
}

public class TwoController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Foo = TempData["foo"] as string
        };
        return View(model);
    }
}

and the corresponding view (~/Views/Two/Index.cshtml):

@model MyViewModel
@Html.DisplayFor(x => x.Foo)


There are drawbacks of using TempData as well: if the user hits F5 on the target page the data will be lost.

Personally I don't use TempData neither. It's because internally it uses Session and I disable session in my applications. I prefer a more RESTful way to achieve this. Which is: in the first controller action that performs the redirect store the object in your data store and user the generated unique id when redirecting. Then on the target action use this id to fetch back the initially stored object:

public class OneController: Controller
{
    public ActionResult Index()
    {
        var id = Repository.SaveData("foo");
        return RedirectToAction("index", "two", new { id = id });
    }
}

public class TwoController: Controller
{
    public ActionResult Index(string id)
    {
        var model = new MyViewModel
        {
            Foo = Repository.GetData(id)
        };
        return View(model);
    }
}

The view stays the same.

这篇关于ViewBag、ViewData 和 TempData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆