ASP. net mvc describes four methods for transferring data from a controller to a view. 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;
Then obtain the value in ViewData in the view and convert the object as follows:
@{ var p = (Products)ViewData["person"];}
Method 2: ViewBag
The methods in the controller are stored in the form of ViewBag 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 ("");}
Steering: Index-Order-Detail, the TempData object cannot be obtained in the Detail method, because TempData can only be passed once and will be automatically cleared by the system.
Output result
Source code download: http://xiazai.jb51.net/201701/yuanma/MvcTest_jb51.rar
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.