ViewData,ViewBag和TempData有什么区别? [英] What is the difference between ViewData, ViewBag and TempData?

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

问题描述

我正在为新项目使用.net mvc 4.0.我想知道ViewData,ViewBag和TempData有什么区别?

I'm using .net mvc 4.0 for my new project. I want to know What is the difference between ViewData, ViewBag and TempData?

我尝试在网上搜索,但找不到任何好的文档材料.

I tried searching on net but didn't find any well document material.

推荐答案

来自十大ASP.NET MVC面试问题

为了将数据从控制器传递到视图以及下一个后续 请求,ASP.NET MVC框架提供了不同的选择,即 ViewData,ViewBag和TempData.

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e., ViewData, ViewBag and TempData.

ViewBag和ViewData均用于在控制器之间进行通信 和相应的视图.但是此通信仅用于服务器 调用,如果发生重定向,它将变为null.简而言之,这是一个 维护控制器和相应视图之间状态的机制.

Both ViewBag and ViewData are used to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism to maintain state between controller and corresponding view.

ViewData是一个字典对象,而ViewBag是一个动态属性( 新的C#4.0功能).作为字典对象的ViewData是可访问的 使用字符串作为键,并且还需要对复杂类型进行类型转换. 另一方面,ViewBag没有类型转换和null检查.

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks.

TempData也是一个字典对象,在 HTTP请求.因此,Tempdata可用于维护之间的数据 从一个控制器重定向到另一个控制器.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the other controller.

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

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