Prelude
1. Under the models file in the new project, create a new products class:
public class Products {public int Id {get; set;} public string Name {get; set;} Public double price {get; set;}}
2. Instantiate this class in the controller
var p = new Products () { Id = 1, Name = "Drink", price = 2.5 };
Way 1:viewdata
Store the method in the controller with ViewData as a key-value pair in the form of a class that stores the instantiated object above, as follows:
viewdata["person"] = p;
Then get the value in the ViewData in the view and convert the object, as follows:
@{ var p = (products) viewdata[' person ';}
Way 2:viewbag
The method in the controller is used to store the above object in the form of a viewbag dynamic expression, as follows:
Viewbag._product = p;
Modify the view as follows:
@{ var p = (products) viewbag._product;}
Way 3:model
Return the method in the controller to the view above object, as follows:
Public ActionResult Index () { var p = new Products () { Id = 1, Name = "Drink", price = 2.5 };
return View (P); }
And we get the mandatory type object in the view products, as follows:
@using mvctest.models; @model products@{ viewbag.title = "Index";}
Mode four: TempData
TempData can continue to be used by steering because its value is stored in the session. However, TempData can only be passed once and then automatically purged by the system.
Below I will demonstrate the shift from the index action to the order action and output the value stored in the TempData in the view.
First, create a new action method in the control, named the order method, the code is as follows:
Public ActionResult Index () { var p = new Products () { Id = 1, Name = "Drink", price = 2.5 };
tempdata["_product"] = p; Return redirecttoaction ("Order"); } Public ActionResult Order () {return View (); }
Modify the view as follows:
@{products p = (products) tempdata["_product";}
Suppose the code in the controller is modified as follows:
Public ActionResult Index () { var p = new Products () { Id = 1, Name = "Drink", price = 2.5 };
tempdata["_product"] = p; Return redirecttoaction ("Order"); } Public ActionResult Order () { return redirecttoaction ("Detail"); } Public ActionResult Detail () {products _product = (products) tempdata["_product"]; Return View (""); }
Steering: Index-order-detail, in the Detail method, the TempData object cannot be obtained because TempData can only be passed once and then automatically purged by the system.
Output results
The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we are more topic.alibabacloud.com.