https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

Confused about Models, Views, and Controllers? In this tutorial, Stephen Walther introduces you to the different parts of an ASP.NET MVC application.

This tutorial provides you with a high-level overview of ASP.NET MVC models, views, and controllers. In other words, it explains the M', V', and C' in ASP.NET MVC.

After reading this tutorial, you should understand how the different parts of an ASP.NET MVC application work together.

You should also understand how the architecture of an ASP.NET MVC application differs from an ASP.NET Web Forms application or Active Server Pages application.

The Sample ASP.NET MVC Application

The default Visual Studio template for creating ASP.NET MVC Web Applications includes an extremely simple sample application that can be used to understand the different parts of an ASP.NET MVC application. We take advantage of this simple application in this tutorial.

You create a new ASP.NET MVC application with the MVC template by launching Visual Studio 2008 and selecting the menu option File, New Project (see Figure 1). In the New Project dialog, select your favorite programming language under Project Types (Visual Basic or C#) and select ASP.NET MVC Web Application under Templates. Click the OK button.

When you create a new ASP.NET MVC application, the Create Unit Test Project dialog appears (see Figure 2).

This dialog enables you to create a separate project in your solution for testing your ASP.NET MVC application.

Select the option No, do not create a unit test project and click the OK button.

After the new ASP.NET MVC application is created. You will see several folders and files in the Solution Explorer window.

In particular, you'll see three folders named Models, Views, and Controllers. As you might guess from the folder names, these folders contain the files for implementing models, views, and controllers.

If you expand the Controllers folder, you should see a file named AccountController.cs and a file named HomeController.cs.

If you expand the Views folder, you should see three subfolders named Account, Home and Shared.

If you expand the Home folder, you'll see two additional files named About.aspx and Index.aspx (see Figure 3).

These files make up the sample application included with the default ASP.NET MVC template.

You can run the sample application by selecting the menu option Debug, Start Debugging. Alternatively, you can press the F5 key.

When you first run an ASP.NET application, the dialog in Figure 4 appears that recommends that you enable debug mode. Click the OK button and the application will run.

When you run an ASP.NET MVC application, Visual Studio launches the application in your web browser.

The sample application consists of only two pages: the Index page and the About page.

When the application first starts, the Index page appears (see Figure 5). You can navigate to the About page by clicking the menu link at the top right of the application.

Notice the URLs in the address bar of your browser. For example, when you click the About menu link, the URL in the browser address bar changes to /Home/About.

If you close the browser window and return to Visual Studio, you won't be able to find a file with the path Home/About. The files don't exist. How is this possible?

A URL Does Not Equal a Page

When you build a traditional ASP.NET Web Forms application or an Active Server Pages application, there is a one-to-one correspondence between a URL and a page. If you request a page named SomePage.aspx from the server, then there had better be a page on disk named SomePage.aspx. If the SomePage.aspx file does not exist, you get an ugly 404 - Page Not Found error.

When building an ASP.NET MVC application, in contrast, there is no correspondence between the URL that you type into your browser's address bar and the files that you find in your application.

In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk.

In a traditional ASP.NET or ASP application, browser requests are mapped to pages.

In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions.

An ASP.NET Web Forms application is content-centric. An ASP.NET MVC application, in contrast, is application logic centric.

Understanding ASP.NET Routing

A browser request gets mapped to a controller action through a feature of the ASP.NET framework called ASP.NET Routing.

ASP.NET Routing is used by the ASP.NET MVC framework to route incoming requests to controller actions.

ASP.NET Routing uses a route table to handle incoming requests.

This route table is created when your web application first starts.

The route table is setup in the Global.asax file.

The default MVC Global.asax file is contained in Listing 1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
); } protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}

When an ASP.NET application first starts, the Application_Start() method is called.

In Listing 1, this method calls the RegisterRoutes() method and the RegisterRoutes() method creates the default route table.

The default route table consists of one route.

This default route breaks all incoming requests into three segments (a URL segment is anything between forward slashes).

The first segment is mapped to a controller name, the second segment is mapped to an action name, and the final segment is mapped to a parameter passed to the action named Id.

For example, consider the following URL:

/Product/Details/3

This URL is parsed into three parameters like this:

Controller = Product

Action = Details

Id = 3

The Default route defined in the Global.asax file includes default values for all three parameters.

The default Controller is Home, the default Action is Index, and the default Id is an empty string.

With these defaults in mind, consider how the following URL is parsed:

/Employee

应该是用string.split来解析,然后按照数组下标赋值,不存在的就用默认值

This URL is parsed into three parameters like this:

Controller = Employee

Action = Index

Id = ��

Finally, if you open an ASP.NET MVC Application without supplying any URL (for example, http://localhost) then the URL is parsed like this:

Controller = Home

Action = Index

Id = ��

The request is routed to the Index() action on the HomeController class.

Understanding Controllers

A controller is responsible for controlling the way that a user interacts with an MVC application.

A controller contains the flow control logic for an ASP.NET MVC application.

A controller determines what response to send back to a user when a user makes a browser request.

A controller is just a class (for example, a Visual Basic or C# class).

The sample ASP.NET MVC application includes a controller named HomeController.cs located in the Controllers folder.

The content of the HomeController.cs file is reproduced in Listing 2.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View();
} public ActionResult About()
{
ViewData["Title"] = "About Page"; return View();
}
}
}

Notice that the HomeController has two methods named Index() and About().

These two methods correspond to the two actions exposed by the controller.

The URL /Home/Index invokes the HomeController.Index() method and the URL /Home/About invokes the HomeController.About() method.

Any public method in a controller is exposed as a controller action.

You need to be careful about this. This means that any public method contained in a controller can be invoked by anyone with access to the Internet by entering the right URL into a browser.

Understanding Views

The two controller actions exposed by the HomeController class, Index() and About(), both return a view.

A view contains the HTML markup and content that is sent to the browser.

A view is the equivalent of a page when working with an ASP.NET MVC application.

You must create your views in the right location.

The HomeController.Index() action returns a view located at the following path:

\Views\Home\Index.aspx

The HomeController.About() action returns a view located at the following path:

\Views\Home\About.aspx

In general, if you want to return a view for a controller action, then you need to create a subfolder in the Views folder with the same name as your controller. Within the subfolder, you must create an .aspx file with the same name as the controller action.

The file in Listing 3 contains the About.aspx view.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>About</h2>
<p>
Put content here.
</p>
</asp:Content>

If you ignore the first line in Listing 3, most of the rest of the view consists of standard HTML. You can modify the contents of the view by entering any HTML that you want here.

A view is very similar to a page in Active Server Pages or ASP.NET Web Forms.

A view can contain HTML content and scripts. You can write the scripts in your favorite .NET programming language (for example, C# or Visual Basic .NET).

You use scripts to display dynamic content such as database data.

Understanding Models

We have discussed controllers and we have discussed views. The last topic that we need to discuss is models. What is an MVC model?

An MVC model contains all of your application logic that is not contained in a view or a controller.

The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

A view should contain only logic related to generating the user interface.

A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control).Everything else should be contained in the model.

In general, you should strive努力 for fat models and skinny controllers.

Your controller methods should contain only a few lines of code.

If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

Summary

This tutorial provided you with a high level overview of the different parts of an ASP.NET MVC web application.

You learned how ASP.NET Routing maps incoming browser requests to particular controller actions.

You learned how controllers orchestrate精心安排 how views are returned to the browser.

Finally, you learned how models contain application business, validation, and database access logic.

Understanding Models, Views, and Controllers (C#)的更多相关文章

  1. Understanding Scroll Views 深入理解 scroll view 读书笔记

    Understanding Scroll Views 深入理解 scroll view  读书笔记   It may be hard to believe, but a UIScrollView is ...

  2. The Three Models of ASP.NET MVC Apps

    12 June 2012  by Dino Esposito by Dino Esposito   We've inherited from the original MVC pattern a ra ...

  3. Object Modeling

    https://developer.apple.com/library/content/documentation/General/Conceptual/CocoaEncyclopedia/Objec ...

  4. MVC 总结

    以下内容摘自 PHP for Absolute Beginners, Thomas Blom Hansen & Jason Lengstorf The model-view-controlle ...

  5. MVC与WebForm的区别

    在初步了解MVC后,发现很多人对于MVC和三层架构开发概念上会有很大的混淆,所以把这两天的学习笔记整理一下,分享给自己的同学们.同时也做一个小Demo,让没有接触过MVC开发的同学,能对MVC有一个简 ...

  6. 解析ASP.NET WebForm和Mvc开发的区别

    因为以前主要是做WebFrom开发,对MVC开发并没有太深入的了解.自从来到创新工场的新团队后,用的技术都是自己以前没有接触过的,比如:MVC 和EF还有就是WCF,压力一直很大.在很多问题都是不清楚 ...

  7. ExtJS笔记3 MVC Architecture

    MVC Architecture   MVC架构 Contents File Structure Creating the application in app.js Defining a Contr ...

  8. Extjs 4.2.0 MVC 架构

    内容: 1. 文件结构 2. 创建项目 3. 定义控制器 4. 定义视图 5. 控制Grid 6. 创建Model和Store 7. 通过Model保存数据 8. 保存到服务器端 大型客户端程序通常都 ...

  9. Asp.net mvc 知多少(七)

    本系列主要翻译自<ASP.NET MVC Interview Questions and Answers >- By Shailendra Chauhan,想看英文原版的可访问http:/ ...

随机推荐

  1. PHP常见算法

    算法的概念:解决特定问题求解步骤的描述,在计算机中表现为指令的有限序列,并且每条指令表示一个或多个操作.一个问题可以有多种算法,每种算法都不同的效率.一个算法具有的特征:有穷,确切,输入,输出,可行 ...

  2. 日语单词N3_N4_N5

    单 词 讲 解 あ行单词 ああ:0[副]那样.那种 例句:ああ言うことはしないほうがいい.那样的事情最好不做. 電車の窓からごみを棄てているああ言うことはしないほうがいい. 挨拶(あいさつ):① 寒暄 ...

  3. perl语言的线程使用

    参考的教程链接是 https://www.cnblogs.com/migrantworkers/p/6973459.html 1.Perl 多线程的使用,join 和 detach 的区别 ,join ...

  4. Windows10+Android Studio 3.5编译项目报错——NDK Resolution Outcome: Project settings: Gradle model version=4.10.1, NDK version is UNKNOWN

    项目背景: 系统有C.D两个盘,Android Studio安装在D盘,sdk安装在C盘. 出现的问题: 从git拉取项目后,一直编译不通过,提示“NDK Resolution Outcome: Pr ...

  5. 程序员与数据库打交道的JDBC知识概要

    1.JDBC全称:Java database connectivity,Java数据库连接. (1)           JDBC是一种用于执行SQL语句的Java API,为多种关系数据库提供多种统 ...

  6. mysql的unsigned属性负值报错和为0情况及mysql的严格模式

    最近发现在进行线程操作时,发现数据库的unsigned字段减为负数时并未报错而是变为0,因此去寻找解决方案,发现这和我的sql_mode有关. sql_mode MySQL服务器可以以不同的SQL模式 ...

  7. 大海航行靠舵手 华为云靠什么征服K8S?

    Kubernetes 是Google开源的容器集群管理系统或者称为分布式操作系统.它构建在Docker技术之上,为容器化的应用提供资源调度.部署运行.服务发现.扩容缩容等整一套功能,本质上可看作是基于 ...

  8. (1)openstack-Rabbitmq 集群部署

    一.前期准备   (1)条件:准备3台linux系统,确保配置好源,及epel源  yun1,yun2,yun3   (2)三台机器能够静态解析彼此   (3)设置可以无密钥登陆  ssh-keyge ...

  9. PAT Basic 1045 快速排序 (25 分)

    著名的快速排序算法里有一个经典的划分过程:我们通常采用某种方法取一个元素作为主元,通过交换,把比主元小的元素放到它的左边,比主元大的元素放到它的右边. 给定划分后的 N 个互不相同的正整数的排列,请问 ...

  10. mongodb的基本操作之数据写入和查询

    连接到mongodb服务器后,查看当前数据中有多少数据库 show dbs   切换数据库 use conf     删除数据库 db.dropDatabase() 再次使用 use conf 切换数 ...