ASP.NET controller TO view 数据传递

https://stackify.com/viewbag/

In the case of ASP.NET MVC, you have three ways to pass data from the controller to the view. These are

  1. ViewBag,
  2. ViewData and
  3. TempData.

ViewBag and ViewData are highly similar in the way they pass data from controller to view, and both are considered as a way to communicate between the view and the controller within a server call. Both of these objects work well when you use external data.

How does one differ from the other? ViewData is a dictionary or listing of objects that you can use to put data into. The data is now accessible to view. It is based on the ViewDataDictionary class. You can use ViewBag around any ViewData object so that you could assign dynamic properties to it, making it more flexible.

You would need typecasting for ViewData and check for null values, but you do not need to typecast complex data types in ViewBag.

ViewBag vs. TempData

TempData, on the other hand, is also a dictionary and it is based on the TempDataDictionary class. It keeps information temporarily, as long as the HTTP request is active. TempData is perfect for redirects and a few other instances because of its temporary nature.

ViewModel

As discussed in the limitations section, there are several types of data where you cannot use ViewBag, primarily those big and complex data sets. For these types of data, you can use ViewModel if you are using ASP.NET MVC.

ViewModel also has a distinct advantage in that it is strongly typed. This means that unlike in ViewBag, ViewModel does not confuse one type with another type. For example, using ViewBag, the compiler will not detect an error when you use a DateTime as if it were a string.

VIewBag:

1. dynamic

2. not strongly typed

原文地址:https://www.cnblogs.com/argenbarbie/p/8080553.html