Transferred from: http://www.cnblogs.com/shinima/p/3940452.html
1. Providing a view model object
You can pass an object to the view as a parameter of the view method.
- Public ViewResult Index ()
- {
- DateTime date = DateTime.Now;
- return View (date);
- }
We then use the Razor model keyword in the view to access the object
- @{
- Viewbag.title = "Index";
- }
-
- The day is : @ ((DateTime) Model). DayOfWeek)
or a
- @model DateTime
- @{
- Viewbag.title = "Index";
- }
-
- The day is : @Model. DayOfWeek
2. Passing Data using ViewBag (view pack)
View Bag allows you to define any property on a dynamic object and access it in a view. This dynamic object can be accessed through the Controller.viewbag property.
- Public ViewResult Index ()
- {
- Viewbag.message = "Hello";
- Viewbag.date = DateTime.Now;
- return View ();
- }
- @{
- Viewbag.title = "Index";
- }
- The day is : @ViewBag. Date.dayofweek
- <p/>
- The message is : @ViewBag. Message
3. Passing Data using view data
Before MVC3.0, the main way to pass data is by using the Viewdatadictionary class instead of a dynamic object. The Viewdatadictionary class is similar to the standard "key/value" collection and is
The ViewData property of the controller class is accessed. This method requires that the object be converted in the view.
- In the controller:
- Public ViewResult Index ()
- {
- viewdata["Message"] = "Hello";
- viewdata["Date"] = DateTime.Now;
- return View ();
- }
- In the View:
- @{
- Viewbag.title = "Index";
- }
- The day is : @ (((DateTime) viewdata["Date"). DayOfWeek)
- <p/>
- The message is : @ViewData ["message"]
Three ways to pass values to the view of the ASP.