ASP. net mvc transmits data from the Controller to the view in four ways. asp. netmvc
Prelude
1. Under the Models file in the new project, create a 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 };
Method 1: ViewData
The method in the controller uses ViewData to store the above instantiated object in the form of a key-value pair, as follows:
ViewData["person"] = p;
ObtainViewDataAnd convert the object as follows:
@{ var p = (Products)ViewData["person"];}Method 2: ViewBag
Use the methods in the ControllerViewBagThe above objects are stored in the form of dynamic expressions, as follows:
ViewBag._Product = p;
Modify the view as follows:
@{ var p = (Products)ViewBag._Product;}Method 3: Model
Return the methods in the Controller to the View object as follows:
Public ActionResult Index () {var p = new Products () {Id = 1, Name = "beverage", Price = 2.5}; return View (p );}
In the view, the forced type object Products is obtained as follows:
@using MvcTest.Models;@model Products@{ ViewBag.Title = "Index";}Method 4: TempData
TempData can be switched to continue to be used because its value is stored in the Session. However, TempData can only be passed once and will be automatically cleared by the system.
The following shows how to change from the Index action to the Order action and output the value stored in TempData in the view.
First, create an Action method in the control and name it the Order method. The Code is as follows:
Public ActionResult Index () {var p = new Products () {Id = 1, Name = "beverage", Price = 2.5}; TempData ["_ product"] = p; return RedirectToAction ("Order");} public ActionResult Order (){
Return View ();}
Modify the view as follows:
@{ Products p = (Products)TempData["_product"];}
Assume that the code in the controller is modified as follows:
Public ActionResult Index () {var p = new Products () {Id = 1, Name = "beverage", 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 ("");}
Turn to Index-Order-Detail. In the Detail method, the TempData object cannot be obtained becauseTempData can only be passed onceAnd is automatically cleared by the system.
Output result
Source code download