Home Backend Development C#.Net Tutorial Introducing how MVC in ASP.NET passes data from controller to view

Introducing how MVC in ASP.NET passes data from controller to view

Aug 16, 2017 pm 02:17 PM
asp.net how controller

This article mainly introduces the four ways ASP.NET MVC transfers data from the controller to the view. It has certain reference value. Interested friends can refer to it.

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; }
  }
Copy after login

2. In the controller Instantiate this class


var p = new Products()
      {
        Id = 1,
        Name = "饮料",
        Price = 2.5
      };
Copy after login

Method 1: ViewData

Use ViewData for methods in the controller in the form of key-value pairs The class stores the above instantiated object, as follows:


ViewData["person"] = p;
Copy after login

Then obtains the value in ViewData in the view and converts the object, as follows:


@{
  var p = (Products)ViewData["person"];
}
<h1>@p.Id</h1>
<h2>@p.Name</h2>
<h3>@p.Price</h3>
Copy after login

Method 2: ViewBag

Use the method in the controller to store the above object in the form of ViewBag dynamic expression, as follows:


ViewBag._Product = p;
Copy after login

Modify the view as follows:


@{
  var p = (Products)ViewBag._Product;
}
Copy after login

Method 3: Model

Place the controller in The method returns the above object of View, as follows:


public ActionResult Index()

    {

      var p = new Products()

      {

        Id = 1,

        Name = "饮料",

        Price = 2.5

      };

      return View(p);

    }
Copy after login

And we get the mandatory type object Products in the view, as follows:


@using MvcTest.Models;
@model Products
@{
  ViewBag.Title = "Index";
}
<h1>@Model.Id</h1>
<h2>@Model.Name</h2>
<h3>@Model.Price</h3>
Copy after login

Method 4: TempData

TempData can continue to be used through redirection because its value is saved in Session. However, TempData can only be passed once and will be automatically cleared by the system afterwards.

Below I will demonstrate switching from Index action to Order action, and output the value stored in TempData in the view.

First create a new 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 = "饮料",
        Price = 2.5
      };
      TempData["_product"] = p;
      return RedirectToAction("Order");
    }
    public ActionResult Order()
    {
      return View();
    }
Copy after login

Modify the view as follows:


@{
  Products p = (Products)TempData["_product"];
}
Copy after login

Assume that the code in the controller is modified as follows:


public ActionResult Index()
    {
      var p = new Products()
      {
        Id = 1,
        Name = "饮料",
        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("");
    }
Copy after login

Turn to: Index — Order — Detail, then it cannot be obtained in the Detail method to the TempData object, because TempData can only be passed once and will be automatically cleared by the system.

Output result

The above is the detailed content of Introducing how MVC in ASP.NET passes data from controller to view. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to properly calibrate your Xbox One controller on Windows 11 How to properly calibrate your Xbox One controller on Windows 11 Sep 21, 2023 pm 09:09 PM

Since Windows has become the gaming platform of choice, it's even more important to identify its gaming-oriented features. One of them is the ability to calibrate an Xbox One controller on Windows 11. With built-in manual calibration, you can get rid of drift, random movement, or performance issues and effectively align the X, Y, and Z axes. If the available options don't work, you can always use a third-party Xbox One controller calibration tool. Let’s find out! How do I calibrate my Xbox controller on Windows 11? Before proceeding, make sure you connect your controller to your computer and update your Xbox One controller's drivers. While you're at it, also install any available firmware updates. 1. Use Wind

How to use CodeIgniter4 framework in php? How to use CodeIgniter4 framework in php? May 31, 2023 pm 02:51 PM

PHP is a very popular programming language, and CodeIgniter4 is a commonly used PHP framework. When developing web applications, using frameworks is very helpful. It can speed up the development process, improve code quality, and reduce maintenance costs. This article will introduce how to use the CodeIgniter4 framework. Installing the CodeIgniter4 framework The CodeIgniter4 framework can be downloaded from the official website (https://codeigniter.com/). Down

Learning Laravel from scratch: Detailed explanation of controller method invocation Learning Laravel from scratch: Detailed explanation of controller method invocation Mar 10, 2024 pm 05:03 PM

Learning Laravel from scratch: Detailed explanation of controller method invocation In the development of Laravel, controller is a very important concept. The controller serves as a bridge between the model and the view, responsible for processing requests from routes and returning corresponding data to the view for display. Methods in controllers can be called by routes. This article will introduce in detail how to write and call methods in controllers, and will provide specific code examples. First, we need to create a controller. You can use the Artisan command line tool to create

What is laravel controller What is laravel controller Jan 14, 2023 am 11:16 AM

In laravel, a controller (Controller) is a class used to implement certain functions; the controller can combine related request processing logic into a separate class. Some methods are stored in the controller to implement certain functions. The controller is called through routing, and callback functions are no longer used; the controller is stored in the "app/Http/Controllers" directory.

Laravel Study Guide: Best Practices for Controller Method Calls Laravel Study Guide: Best Practices for Controller Method Calls Mar 11, 2024 am 08:27 AM

In the Laravel learning guide, calling controller methods is a very important topic. Controllers act as a bridge between routing and models and play a vital role in the application. This article will introduce the best practices for controller method calling and provide specific code examples to help readers better understand. First, let's understand the basic structure of controller methods. In Laravel, controller classes are usually stored in the app/Http/Controllers directory. Each controller class contains multiple

How to use controllers to handle Ajax requests in the Yii framework How to use controllers to handle Ajax requests in the Yii framework Jul 28, 2023 pm 07:37 PM

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework

How to use parameters of controller in Symfony framework? How to use parameters of controller in Symfony framework? Jun 04, 2023 pm 03:40 PM

Symfony framework is a popular PHP framework designed based on MVC (Model-View-Controller) architecture. In Symfony, controllers are one of the key components responsible for handling web application requests. Parameters in controllers are very useful when processing requests. This article will introduce how to use controller parameters in the Symfony framework. Basic knowledge of controller parameters Controller parameters are passed to the controller through routing. Routing is a mapping of URIs (Uniform Resource Identifiers) to controllers and

Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Jan 02, 2024 pm 08:54 PM

What are the employment prospects of clinical pharmacy at Harbin Medical University? Although the national employment situation is not optimistic, pharmaceutical graduates still have good employment prospects. Overall, the supply of pharmaceutical graduates is less than the demand. Pharmaceutical companies and pharmaceutical factories are the main channels for absorbing such graduates. The demand for talents in the pharmaceutical industry is also growing steadily. According to reports, in recent years, the supply-demand ratio for graduate students in majors such as pharmaceutical preparations and natural medicinal chemistry has even reached 1:10. Employment direction of clinical pharmacy major: After graduation, students majoring in clinical medicine can engage in medical treatment, prevention, medical research, etc. in medical and health units, medical research and other departments. Employment positions: Medical representative, pharmaceutical sales representative, sales representative, sales manager, regional sales manager, investment manager, product manager, product specialist, nurse

See all articles