当前位置:网站首页>[MVC&Core]ASP. Introduction to net core MVC view value transfer
[MVC&Core]ASP. Introduction to net core MVC view value transfer
2022-06-11 00:21:00 【Xiamen dezai】
Preface
1、 The main content of this tutorial
- ASP.NET Core MVC View engine (Razor) brief introduction
- ASP.NET Core MVC View (Razor)ViewData Examples of use
- ASP.NET Core MVC View (Razor)ViewBag Examples of use
- ASP.NET Core NVC View (Razor) Strongly typed values (ViewModel) Page example
2、 Environment information for this tutorial
| Software / Environmental Science | explain |
|---|---|
| operating system | Windows 10 |
| SDK | 2.1.401 |
| ASP.NET Core | 2.1.3 |
| IDE | Visual Studio Code 1.28 |
| browser | Chrome 70 |
This code is adjusted based on the following code :https://github.com/ken-io/asp.net-core-tutorial/tree/master/chapter-02
3、 Pre knowledge
What you may need to know
- MVC frame / Model is introduced
https://baike.baidu.com/item/mvc
4、 preparation
VS Code Itself does not provide ASP.NET Core MVC View engine (Razor) Intelligent perception .
Fortunately, ,VS Code C# Expand from 1.17.0 Version starting support Razor View engine intellisense .
therefore , We're going to VS Code C# Extend upgrade to the latest version .
Two 、ASP.NET Core MVC View engine (Razor) brief introduction
1、ASP.NET Core MVC View engine (Razor) summary
stay MVC In architecture mode , View engine / The template engine is responsible for the controller (Controller) The data provided is combined with the view template to render the format we need ( Usually HTML). controller (Controller) And then return the rendered results to the requesting client .
stay ASP.NET Core MVC In the frame , Provides a view engine :Razor.
Razor The suffix provided is .cshtml View template for .Razor View templates support the use of Razor Markup language and C# Compiling . It is very convenient to use .
Razor Equivalent to Java Platform commonly used Freemarker、Thymeleaf
2、Razor View template file location and assignment
View file location
Razor View template files are usually placed in the root directory Views The folder corresponds to a subdirectory of the controller .
for example : ~/Views/Home/Time.cshtml.
This is because according to ASP.NET Core MVC Framework Agreement , When we are in the controller (Controller) Return a view (return View();) when , If only the view name is specified (ViewName), No view completion path is specified , that MVC The framework will find the views in the following order :
- Views/[ControllerName]/[ViewName].cshtml
- Views/Shared/[ViewName].cshtml
How views are specified
Implicitly specify
public class HomeController : Controller
{
public IActionResult Test(){
return View();
}
}
When not specified ViewName When ,ViewName=ActionName=”Test”;
The framework will look for the view files in the agreed order
- Displays the specified view name
public class HomeController : Controller
{
public IActionResult Test(){
return View("Test");
}
public IActionResult TestAbc(){
return View("abc");
}
}
The view names are manually specified ;ViewName=”Test”、ViewName=”abc”;
The framework will look for the view files in the agreed order
- Displays the specified view file
public class HomeController : Controller
{
public IActionResult Test(){
return View("Views/Test.cshtml");
}
}
Fixed search Views/Test.cshtml view file
3、 ... and 、Razor The view engine passes data
1、 preparation
- establish RenderDataController
stay Controllers Add controller under folder RenderDataController.cs And inherited from Controller
using System;
using Microsoft.AspNetCore.Mvc;
namespace Ken.Tutorial.Web.Controllers
{
public class RenderDataController : Controller
{
}
}
- Create the corresponding view folder
stay Views Create a folder in the directory RenderData
2、 Weakly typed parameters pass data
Weak type parameter description
- ViewData
- Derive from ViewDataDictionary, So it has available dictionary properties , Such as ContainsKey、Add、Remove and
Clear. - The key in the dictionary is a string , Therefore, spaces are allowed . Example :ViewData[“ken”]
- Anything that is not string Types must be cast in the view to use ViewData.
- ViewBag
- Derive from DynamicViewData, So it can use point notation (@ViewBag.SomeKey = )
Create dynamic attributes , And there is no need to cast . - ViewBag The syntax of makes adding to controllers and views faster .
- ViewBag Easier to check NULL value . Example :@ViewBag.Person?.Name
ViewData Examples of use
- establish Action:ViewDataDemo
public IActionResult ViewDataDemo()
{
ViewData["name"] = "ken";
ViewData["birthday"] = new DateTime(2000, 1, 1);
ViewData["hobby"] = new string[] {
" running ", " read ", "Coding" };
return View();
}
- Create view :ViewDataDemo.cshtml
@{
var hobby =ViewData["hobby"] as String[];
}
<h3>@ViewData["title"]</h3>
<ul>
<li> full name :@ViewData["name"]</li>
<li> Birthday :@ViewData["birthday"]</li>
<li> hobby :@hobby[0] , @hobby[1]</li>
</ul>
- Access test
Start project , visit /renderdata/viewdatademo You will see :

ViewBag Examples of use
- establish Action:ViewBagDemo
public IActionResult ViewBagDemo()
{
ViewBag.Title = "ViewBag Example of value transfer ";
ViewBag.Name = "ken";
ViewBag.Birthday = new DateTime(2000, 1, 1);
ViewBag.Hobby = new string[] {
" running ", " read ", "Coding" };
return View();
}
- Create view :ViewBagDemo.cshtml
@{
var hobby =ViewBag.Hobby as String[];
}
<h3>@ViewBag.Title</h3>
<ul>
<li> full name :@ViewBag.Name</li>
<li> Birthday :@ViewBag.Birthday</li>
<li> hobby :@hobby[0] , @hobby[1]</li>
</ul>
- Access test
Start project , visit /renderdata/viewbagdemo You will see :

3、 Strongly typed parameters pass data
Strong type parameter description
View strong typing is often called ViewModel, We can do it in return View(); Specify view parameters when / object . And in the view file (.cshtml) Pass through @model The syntax specifies the corresponding type , In this way, we can create a view file (.cshtml) Use in Model Keyword to use instances of this type that are transferred to the view .
Strongly typed parameter example
- establish Person class
Create in project root Models Folder and create... In the file Person.cs
using System;
namespace Ken.Tutorial.Web.Models
{
public class Person
{
public string Name {
get; set; }
public DateTime Birthday {
get; set; }
public string[] Hobby {
get; set; }
}
- establish Action:ViewModelDemo
public IActionResult ViewModelDemo()
{
ViewBag.Title = "ViewModel Example of value transfer ";
var person = new Person
{
Name = "ken",
Birthday = new DateTime(2000, 1, 1),
Hobby = new string[] {
" running ", " read ", "Coding" }
};
// Equate to return View("ViewModelDemo", person);
return View(person);
}
- Create view :ViewModelDemo.cshtml
@model Ken.Tutorial.Web.Models.Person;
<h3>@ViewBag.Title</h3>
<ul>
<li> full name :@Model.Name</li>
<li> Birthday :@Model.Birthday</li>
<li> hobby :@Model.Hobby[0] , @Model.Hobby[1]</li>
</ul>
- Access test
Start project , visit /renderdata/viewmodeldemo You will see :

Four 、 remarks
1、 appendix
Sample code for this article
https://github.com/ken-io/asp.net-core-tutorial/tree/master/chapter-05
In this paper, the reference
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/overview?view=aspnetcore-2.1
边栏推荐
- MySQL command line import and export data
- About optimizing API interface response speed
- Bluetooth development (3) -- look at the air bag
- Excel单元格
- Bluetooth development (2) -- initialization
- mysql 数据库 表 备份
- phpstudy的安装
- USB IP core FPGA debugging (I)
- [database] MySQL index interview questions
- 【Pygame小游戏】《坦克大战》,那些童年的游戏你还记得几个呢?
猜你喜欢

Leetcode-15 sum of three numbers

Go语言Channel理解使用

Leetcode-713 subarray with product less than k

Exemple VTK - - trois plans qui se croisent

【JVM】垃圾回收机制
![[opencv practice] in cold winter, there will be a rainbow. Do you love this special effect?](/img/24/40c299b023f5f8d781d11296bcf28a.png)
[opencv practice] in cold winter, there will be a rainbow. Do you love this special effect?

Yum source update

【无标题】测试下啊

【自动回复or提醒小助手】妈妈再也不用担心我漏掉消息了(10行代码系列)
![[pyGame games] in the first month, it broke 100 million to download a masterpiece that is highly integrated with](/img/f5/d947f5e5c2abf79c0fac2f45103ec0.png)
[pyGame games] in the first month, it broke 100 million to download a masterpiece that is highly integrated with "super casual game features"~
随机推荐
Multipass中文文档-教程
字符串时间排序,对时间格式字符串进行排序
Njupt Nanyou Discrete Mathematics_ Experiment 1
Multipass Chinese document - instructions for use (contents page)
[JVM] garbage collection mechanism
什么是绝对和相对路径,有哪些优缺点?
Unity自定义文件夹图标颜色 个性化Unity编译器
安全生产月,黄埔开展燃气安全进商铺宣传活动
CSDN daily practice -- half search of ordered table
Leetcode-560 and subarray with K
静态方法static学习
[daily] robots Txt allow all search engines to include
763. dividing alphabetic intervals
[pyGame] stir up your brain and play the "24 o'clock" idea together ~ (awesome)
333333
电脑录屏免费软件gif等格式视频
Canvas drawing line break
Lambda learning records
array_column() expects parameter 1 to be array, array given
Leetcode-209 minimum length subarray