我在MVC 3中看到了ViewBag。这和MVC 2中的ViewData有什么不同?


当前回答

通过这种方式,我们可以让它使用这些值来将控制器之间的信息传递到带有TEMP DATA的其他页面

其他回答

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}

public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 

In View:

@ViewBag.Name 
@ViewData["Name"] 

通过这种方式,我们可以让它使用这些值来将控制器之间的信息传递到带有TEMP DATA的其他页面

下面是关于ViewData, ViewBag, TempData和Session的点对点差异。 信贷/ askforprogram复制。在这里,遵循我没有提到的代码示例的链接。

ViewData in MVC ViewData is property of ControllerBase class. ViewData is a type of dictionary object. ViewData is key-value dictionary collection. ViewData was introduced in MVC 1.0 version. ViewData works with .Net framework 3.5 and above. Need to do type conversion of code while enumerating. ViewData object keeps data only for current request. ViewBag in MVC ViewBag is property of ControllerBase class. ViewBag is a type of dynamic object. ViewBag is a type of object. ViewBag was introduced in MVC 3.0 version. ViewBag works with .Net framework 4.0 and above. ViewBag uses property and handles it, so no need to do type conversion while enumerating. ViewBag object keeps data only for current request. TempData in MVC TempData is property of ControllerBase class. TempData is a type of dictionary object. TempData is key-value dictionary collection. TempData was introduced in MVC 1.0 version. TempData works with .Net framework 3.5 and above. Need to do type conversion of code while enumerating. TempData object is used to data between current request and subsequent request. Session in MVC Session is property of Controller(Abstract Class). Session is a type of HttpSessionStateBase. Session is key-value dictionary collection. Session was introduced in MVC 1.0 version. TempData works with .Net framework 1.0 and above. Need to do type conversion of code while enumerating. Session object keeps data for all requests. Valid for all requests, never expires.

ViewData

ViewData用于将数据从控制器传递给ViewData,它是从viewdatdictionary类派生出来的。仅对当前请求可用。仅要求复杂数据类型的类型转换,并检查null值以避免错误。如果发生重定向,则其值为null

ViewBag

ViewBag是一个动态属性,它利用了c# 4.0中的新动态特性。它也仅对当前请求可用。如果发生重定向,则其值为null

ViewBag

它返回Type Object。 它是ControllerBase类的一个动态属性。 ViewBag仅适用于。net Framework 4.0及以上版本。 因为ViewBag属性本质上是动态的,所以在使用前不需要进行类型转换。 ViewBag返回动态类型对象,它的属性也是动态的。 它比ViewData快一点。

显示数据

它返回键值字典对集合。 ViewData是一个字典对象,它是ControllerBase类的属性。 ViewData比ViewBag快。 类型转换代码在枚举时是必需的,因为它是字典对集合。 ViewData返回对象(键值对的类型和值是类型对象,所以在使用前需要转换)


public ActionResult Index()
{   
    ViewBag.Name = "";   
    return View();
}

public ActionResult Index()
{  
    ViewData["Name"] = "Arun Prakash";  
    return View();
}

视图呼叫

@ViewBag.Name    
@ViewData["Name"]