当前位置:网站首页>[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获取IMAQ Get Last Event坐标
- LabVIEW用高速数据流盘
- LabVIEW用VISA Read函数来读取USB中断数据
- LabVIEW调用DLL时出现异常0xc0000005代码
- Self made app connected to onenet --- realize data monitoring and distribution control (mqtt)
- LabVIEW改变Point ROI Overlay的形状或颜色
- Quick sort
- [pyGame games] don't look for it. Here comes the leisure game topic - bubble dragon widget - recommendation for leisure game research and development
- LabVIEW error "memory full - Application stopped on node"
- MySQL命令行导入导出数据
猜你喜欢
![[AI card player] for the first time to see such an](/img/7b/f1965a74733e152dcc542e465112b0.png)
[AI card player] for the first time to see such an "exciting" landowner, the key factor for a high winning rate is

Dark horse headlines - Tencent's salary system reform has caused controversy; Intel expanded the recruitment of female engineers nationwide; Black horse is 100% employed really
![[pyGame] can the little dinosaur on chrome be played with code? It looks like fun~](/img/b4/a4140eb10658af40a8a2fc0f428b0f.jpg)
[pyGame] can the little dinosaur on chrome be played with code? It looks like fun~

【自动回复or提醒小助手】妈妈再也不用担心我漏掉消息了(10行代码系列)

LabVIEW错误“内存已满 - 应用程序停止在节点”
![[pyGame games] story stream recommendation: what kind of games can you like? (devil lover, bully's wife version)](/img/77/653968895434f805d81a10406dcf6f.png)
[pyGame games] story stream recommendation: what kind of games can you like? (devil lover, bully's wife version)

30 | how to reset the consumer group displacement?

LabVIEW改变Point ROI Overlay的形状或颜色

【Pygame小游戏】激荡大脑思维,一起来玩转奇思妙想“24点”叭~(超赞滴)

IGBT与三代半导体SiC双脉冲测试方案
随机推荐
csdn每日一练——找出最接近元素并输出下标
归并排序
【LaTex】latex VS Code snippets(代码片段)
Basic introduction and core components of kubernetes
Quick sort
Pseudo static setting of Typecho - starze V Club
[pyGame games] tank battle, how many childhood games do you remember?
Hyperleger fabric installation
CSDN daily practice -- half search of ordered table
都说验证码是爬虫中的一道坎,看我只用五行代码就突破它。
Difference between oscilloscope and spectrum analyzer
选择排序
【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)
IGBT and third generation semiconductor SiC double pulse test scheme
[latex] latex vs Code Snippets
How to measure the refresh rate of oscilloscope
Opencv实战之图像的基本操作:这效果出来惊艳了众人(附代码解析)
[pyGame] this classic bomber super game is online. Do you love it? (source code attached)
Self made app connected to onenet --- realize data monitoring and distribution control (mqtt)
Serial port missing in Ni Max in LabVIEW