ASP.NET Core MVC是一种十分经典的软件设计模式架构,接下来我们来了解一下MVC在ASP.NET8中的一些基础概念。
MVC架构
MVC架构主要包含以下三层:
M(Model):模型层,其职责为UI显示以及业务逻辑或操作所需要的实体对象模型,一般与数据库表存在映射关系。
V(View):视图层,其职责为人机交互页面,展示以及操作数据。
C(Controller):控制器层,其职责为处理数据交互以及业务逻辑,为数据与UI进行交互的一层。
MVC架构引用关系如下:

创建MVC项目
详情查看第二章使用模板创建.NET Core Web
控制器
在MVC中控制器是用来处理用户输入和交互并进行响应的。
添加控制器
选中Controllers文件夹------>右键------>添加------>控制器

选择空控制器

输入控制器名称后点击添加

添加成功后的控制器代码

为控制器添加视图
选中Index方法------>右键------>添加视图

添加Razor视图-空


Views/Test目录下生成了刚才Index方法的视图
生成规则:Vilews/控制器名称/方法名

视图
在Index.cshtml页面中添加以下代码:
cs
@{
ViewData["Title"] = "Test Page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1>
</div>
启动应用并在URL后添加/Test(控制器名称),会命中TestController控制器下的Index方法所绑定的视图。展示效果如下图:

在布局页面(Views/Shared/_Layout.cshtml)添加刚才新加的视图的入口

在asp.net core mvc中a标签内插入asp-area="" asp-controller="Test" asp-action="Index"表示跳转到Test控制器的Index方法
html
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Test" asp-action="Index">Test</a>
</li>
将上面代码插入到标红的代码处

点击Test进入到Test控制器的Index页面

模型
选中Models文件夹------>右键------>添加------>类

输入类名------>点击添加

在新建的类中输入以下代码
cs
public class TestModel
{
public int Id { get; set; }
public string Message { get; set; }
}
修改Test控制器代码创建一个model实例并返回给视图
cs
public class TestController : Controller
{
public IActionResult Index()
{
TestModel model = new TestModel()
{
Id = 1,
Message = "Hello,Test Message"
};
return View(model);
}
}
修改Test\Index.cshtml代码,通过@model指令指定视图对象类型,并通过@HTML辅助标签来访问控制器中返回给视图的model实例
cs
@model TestModel
@{
ViewData["Title"] = "Test Page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1>
<h1 class="display-4">ID:@Html.DisplayFor(model=>model.Id)</h1>
<h1 class="display-4">Message:@Html.DisplayFor(model => model.Message)</h1>
</div>
访问结果如图
