当前位置:网站首页>[MVC&Core]ASP.NET Core MVC 视图传值入门
[MVC&Core]ASP.NET Core MVC 视图传值入门
2022-06-10 22:47:00 【厦门德仔】
前言
1、本教程主要内容
- ASP.NET Core MVC 视图引擎(Razor)简介
- ASP.NET Core MVC 视图(Razor)ViewData使用示例
- ASP.NET Core MVC 视图(Razor)ViewBag使用示例
- ASP.NET Core NVC视图(Razor)强类型传值(ViewModel)页示例
2、本教程环境信息
| 软件/环境 | 说明 |
|---|---|
| 操作系统 | Windows 10 |
| SDK | 2.1.401 |
| ASP.NET Core | 2.1.3 |
| IDE | Visual Studio Code 1.28 |
| 浏览器 | Chrome 70 |
本篇代码基于以下代码进行调整:https://github.com/ken-io/asp.net-core-tutorial/tree/master/chapter-02
3、前置知识
你可能需要的前置知识
- MVC框架/模式介绍
https://baike.baidu.com/item/mvc
4、准备工作
VS Code 本身不提供 ASP.NET Core MVC 视图引擎(Razor)的智能感知。
幸运的是,VS Code C#扩展 从 1.17.0 版本开始支持Razor视图引擎的智能感知。
所以,我们要将VS Code C#扩展升级到最新版本。
二、ASP.NET Core MVC 视图引擎(Razor)简介
1、ASP.NET Core MVC 视图引擎(Razor)概述
在MVC架构模式中,视图引擎/模板引擎负责将控制器(Controller)提供的数据结合视图模板进行渲染我们需要的格式(通常是HTML)。控制器(Controller)再将渲染的结果返回给请求的客户端。
在 ASP.NET Core MVC框架中,提供了视图引擎:Razor。
Razor提供了后缀为.cshtml的视图模板。Razor视图模板支持使用Razor标记语言以及C#进行编写。使用起来非常方便。
Razor 就相当于Java平台常用的 Freemarker、Thymeleaf
2、Razor视图模板文件位置与指定
视图文件位置
Razor视图模板文件通常放在根目录Views文件夹对应控制器的子目录中。
例如: ~/Views/Home/Time.cshtml。
这是因为按照 ASP.NET Core MVC框架的约定,当我们在控制器(Controller)返回一个视图(return View();)时,如果只指定了视图名称(ViewName),并没有指定视图的完成路径,那么MVC框架将按照以下顺序查找视图:
- Views/[ControllerName]/[ViewName].cshtml
- Views/Shared/[ViewName].cshtml
视图指定方式
隐式指定
public class HomeController : Controller
{
public IActionResult Test(){
return View();
}
}
当没有指定ViewName的时候,ViewName=ActionName=”Test”;
框架将按照约定顺序查找视图文件
- 显示指定视图名
public class HomeController : Controller
{
public IActionResult Test(){
return View("Test");
}
public IActionResult TestAbc(){
return View("abc");
}
}
分别手动指定了视图名;ViewName=”Test”、ViewName=”abc”;
框架将按照约定顺序查找视图文件
- 显示指定视图文件
public class HomeController : Controller
{
public IActionResult Test(){
return View("Views/Test.cshtml");
}
}
固定查找 Views/Test.cshtml 视图文件
三、Razor视图引擎传递数据
1、准备工作
- 创建RenderDataController
在Controllers文件夹下新增控制器RenderDataController.cs并继承于Controller
using System;
using Microsoft.AspNetCore.Mvc;
namespace Ken.Tutorial.Web.Controllers
{
public class RenderDataController : Controller
{
}
}
- 创建对应视图文件夹
在Views目录下创建文件夹RenderData
2、弱类型参数传递数据
弱类型参数说明
- ViewData
- 派生自 ViewDataDictionary,因此它有可用的字典属性,如 ContainsKey、Add、Remove 和
Clear。 - 字典中的键是字符串,因此允许有空格。 示例:ViewData[“ken”]
- 任何非 string 类型均须在视图中进行强制转换才能使用 ViewData。
- ViewBag
- 派生自 DynamicViewData,因此它可使用点表示法 (@ViewBag.SomeKey = )
创建动态属性,且无需强制转换。 - ViewBag 的语法使添加到控制器和视图的速度更快。
- ViewBag 更易于检查 NULL 值。 示例:@ViewBag.Person?.Name
ViewData使用示例
- 创建Action:ViewDataDemo
public IActionResult ViewDataDemo()
{
ViewData["name"] = "ken";
ViewData["birthday"] = new DateTime(2000, 1, 1);
ViewData["hobby"] = new string[] {
"跑步", "阅读", "Coding" };
return View();
}
- 创建视图:ViewDataDemo.cshtml
@{
var hobby =ViewData["hobby"] as String[];
}
<h3>@ViewData["title"]</h3>
<ul>
<li>姓名:@ViewData["name"]</li>
<li>生日:@ViewData["birthday"]</li>
<li>爱好:@hobby[0] , @hobby[1]</li>
</ul>
- 访问测试
启动项目,访问 /renderdata/viewdatademo 将会看到:

ViewBag使用示例
- 创建Action:ViewBagDemo
public IActionResult ViewBagDemo()
{
ViewBag.Title = "ViewBag传值示例";
ViewBag.Name = "ken";
ViewBag.Birthday = new DateTime(2000, 1, 1);
ViewBag.Hobby = new string[] {
"跑步", "阅读", "Coding" };
return View();
}
- 创建视图:ViewBagDemo.cshtml
@{
var hobby =ViewBag.Hobby as String[];
}
<h3>@ViewBag.Title</h3>
<ul>
<li>姓名:@ViewBag.Name</li>
<li>生日:@ViewBag.Birthday</li>
<li>爱好:@hobby[0] , @hobby[1]</li>
</ul>
- 访问测试
启动项目,访问 /renderdata/viewbagdemo 将会看到:

3、强类型参数传递数据
强类型参数说明
视图强类型通常称为ViewModel,我们可以在return View();时指定视图参数/对象。并在视图文件(.cshtml)中通过 @model 语法指定对应的类型,这样我们可以在视图文件(.cshtml)中使用Model关键字来使用传输到视图的该类型的实例。
强类型参数示例
- 创建Person类
在项目根目录创建Models文件夹并在文件中创建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; }
}
- 创建Action:ViewModelDemo
public IActionResult ViewModelDemo()
{
ViewBag.Title = "ViewModel传值示例";
var person = new Person
{
Name = "ken",
Birthday = new DateTime(2000, 1, 1),
Hobby = new string[] {
"跑步", "阅读", "Coding" }
};
//等同于 return View("ViewModelDemo", person);
return View(person);
}
- 创建视图:ViewModelDemo.cshtml
@model Ken.Tutorial.Web.Models.Person;
<h3>@ViewBag.Title</h3>
<ul>
<li>姓名:@Model.Name</li>
<li>生日:@Model.Birthday</li>
<li>爱好:@Model.Hobby[0] , @Model.Hobby[1]</li>
</ul>
- 访问测试
启动项目,访问 /renderdata/viewmodeldemo 将会看到:

四、备注
1、附录
本文代码示例
https://github.com/ken-io/asp.net-core-tutorial/tree/master/chapter-05
本文参考
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/overview?view=aspnetcore-2.1
边栏推荐
- LabVIEW displays the time and date on the waveform chart or waveform chart
- LabVIEW图片在从16位强制转换为8位后看起来要亮或暗
- Openresty installation
- LabVIEW获取Clamp函数找到的所有点的信息
- 【Opencv实战】这个印章“神器”够牛,节省了时间提高了效率,厉害~(附完整源码)
- Basic operation of OpenCV actual combat image: this effect amazed everyone (with code analysis)
- CSDN daily practice -- half search of ordered table
- LabVIEW中创建毫秒时间标识
- LabVIEW和VDM提取色彩和生成灰度图像
- 【Opencv实战】寒冷的冬季,也会迎来漫天彩虹,这特效你爱了嘛?
猜你喜欢

IGBT与三代半导体SiC双脉冲测试方案

示波器和频谱分析仪的区别
![[pyGame collection] please check the game guide through childhood: are there any games you have played? (attach five source codes for self access)](/img/f8/e71a1524f73364053952099e7b9588.png)
[pyGame collection] please check the game guide through childhood: are there any games you have played? (attach five source codes for self access)

LabVIEW uses the visa read function to read USB interrupt data

LabVIEW displays the time and date on the waveform chart or waveform chart
![[pyGame] this](/img/7c/adc13c0c87ca31c8581d68e6f21363.jpg)
[pyGame] this "groundhog" game is going to be popular (come on, come on)
![[fireworks in the sky] it's beautiful to light up the night sky with gorgeous fireworks. A programmer brought a fireworks show to pay New Year's greetings to everyone~](/img/3b/2fcd5ff2ea08c4c63428899babd522.png)
[fireworks in the sky] it's beautiful to light up the night sky with gorgeous fireworks. A programmer brought a fireworks show to pay New Year's greetings to everyone~

黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......
![[pyGame games] I'm not afraid you can't walk the maze series: the ultimate AI walks the maze. After learning, it will take you to open the door to a new world ~ (with game source code)](/img/57/dcf291b044b5e5860a7fdc817076d5.jpg)
[pyGame games] I'm not afraid you can't walk the maze series: the ultimate AI walks the maze. After learning, it will take you to open the door to a new world ~ (with game source code)

【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)
随机推荐
Openresty installation
Common settings for vs
Method of converting file to multipartfile
flutter 如何去掉listview顶部空白的问题
Quick sort
Ilruntime hotfix framework installation and breakpoint debugging
Top ten information security principles
vtk.js中vtp下载
Self made app connected to onenet --- realize data monitoring and distribution control (mqtt)
干货丨MapReduce的工作流程是怎样的?
Redis installation and common problem solving based on centeros7 (explanation with pictures)
Flowable process deployment
LabVIEW用高速数据流盘
[latex] latex vs Code Snippets
【Pygame小遊戲】別找了,休閑遊戲專題來了丨泡泡龍小程序——休閑遊戲研發推薦
30 | 怎么重设消费者组位移?
Judgment and other issues: how to determine whether the judgment of the procedure is correct?
LabVIEW打开其他EXE程序
Multipartfile rename upload
[pyGame games] in the first month, it broke 100 million to download a masterpiece that is highly integrated with "super casual game features"~