MVC 基础

正如其名字所示,MVC 有三个组件:模型、视图、和控制器。控制器处理从客户端浏览器传入的请求,并选定相应的代码进行处理。视图就是模板(一般是 HTML 外加某种 Handlebars、Pug、Razor 之类的模板语言),它接收传入的数据并展示给用户。模型则保管着数据,要么是准备发送给视图的,要么是用户输入的。

MVC 程序里常见的模式是:

  • 控制器接收请求,到数据库查找所需资料
  • 控制器使用查找到的信息创建模型,并使之与一个视图绑定
  • 用户点击一个按钮或者提交一个表单,从而发送一个新的请求给控制器,重复整个处理流程

如果你用其它开发语言写过 MVC,那你在 ASP.NET Core 里将如鱼得水。如果你是初次跟 MVC 打交道,这一章将教你基础知识,带你上道。

通读本书,你将构建一个待办清单应用,允许用户添加待办项,并在事项完成之后勾掉它。具体来说,你将创建的是:

  • 一个 web 应用程序服务器(有时也被称为“后端”),使用 ASP.NET Core、C#和MVC模式
  • 一个用于存储用户待办事项条目的数据库,使用 SQLite 数据库引擎和一个被称为 Entity Framework Core 的系统创建
  • 让用户通过她们的浏览器进行交互的网页和界面(也被称为“前端”),使用HTML、CSS、JavaScript创建
  • 一个登录及安全检查表单,以便每个用户的待办事项列表都保持私密

听起来心动吗?那就整起来吧!你要是还没按上一章所讲,用 创建一个新的 ASP.NET Core 项目。那你应该现在就创建并运行那个项目,直到看见默认的欢迎页面为止。


MVC basics

In this chapter, you’ll explore the MVC system in ASP.NET Core. MVC (Model-View-Controller) is a pattern for building web applications that’s used in almost every web framework (Ruby on Rails and Express are popular examples), plus frontend JavaScript frameworks like Angular. Mobile apps on iOS and Android use a variation of MVC as well.

A common pattern for MVC code is:

  • The controller creates a model with the information and attaches it to a view
  • The view is rendered and displayed in the user’s browser
  • The user clicks a button or submits a form, which sends a new request to the controller, and the cycle repeats

If you’ve worked with MVC in other languages, you’ll feel right at home in ASP.NET Core MVC. If you’re new to MVC, this chapter will teach you the basics and will help get you started.

What you’ll build

The “Hello World” exercise of MVC is building a to-do list application. It’s a great project since it’s small and simple in scope, but it touches each part of MVC and covers many of the concepts you’d use in a larger application.

  • A web application server (sometimes called the “backend”) using ASP.NET Core, C#, and the MVC pattern
  • A database to store the user’s to-do items using the SQLite database engine and a system called Entity Framework Core
  • A login form and security checks so each user’s to-do list is kept private

Sound good? Let’s built it! If you haven’t already created a new ASP.NET Core project using dotnet new mvc, follow the steps in the previous chapter. You should be able to build and run the project and see the default welcome screen.