何时使用ViewBag,ViewData的,或在TempData的MVC3 [英] When to use ViewBag, ViewData, or TempData in Mvc3

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

问题描述

当在视图中使用ViewBag,ViewData的,或TempData的。
在控制器我想送的对象到view.I想知道,这将是最好的在这种情况下。
我想在视图页面的对象。

When to use ViewBag, ViewData, or TempData in view. In the controller i want to send object to the view.I want to know that which will be best in this case. I want the object in the view page.

推荐答案

使用TempData的,当你需要的数据可用于下一个请求,仅

Use TempData when you need data to be available for the next request, only.

TempData["myInfo"] = "my info";

然后在接下来的请求时,它会在那里......但在那之后将不复存在。

Then in the next request, it will be there... but will be gone after that.

使用ViewBag对于大多数的额外数据需要传递到您的视图,超越@model

Use ViewBag for most of your extra-data needs to pass to your view, beyond the @model

ViewBag.MyInfo = "my info";

然后从视图访问它。

Then access it from your view.

使用的ViewData访问/输入完全相同的信息作为ViewBag,除了作为一个集合,而不是一个动态对象的属性。

Use ViewData to access/enter the exact same info as ViewBag, except as a collection instead of properties of a dynamic object.

ViewData["MyInfo"]

访问完全相同的数据作为ViewBag.MyInfo

accesses exactly the same data as ViewBag.MyInfo

请注意,我用字符串,但这些可以存储任何你希望的对象。

Note that I used strings, but these can store any object you wish.

另外一点要注意:TempData的和ViewData的是存储对象的值都字典,因此当你使用它们必须转换那些他们原来的类型。然而ViewBag使用动态,而你并不总是需要转换的,因为它是在运行时完成。有些方法(如扩展方法)无法处理动态的,所以你需要在这些案件中投。

Another thing to note: TempData and ViewData are both dictionaries that store object values, so you must cast those to their original type when you use them. ViewBag however uses dynamic, and you don't always need to cast that, since it is done at runtime. Some methods (like Extension methods) can not handle dynamic though, so you would need to cast in those cases.

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

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