search
HomeBackend DevelopmentC#.Net TutorialUnderstand models, views and controllers (C#, asp.net)

This article provides you with a high-level overview of ASP.NET MVC models, views, and controls. In other words, explain ‘M’, ‘V’, and ‘C’ in ASP.NET MVC.

After reading this article, you should be able to understand how the different parts of ASP.NET MVC work together. And you should also be able to understand how the architecture of an ASP.NET MVC program is different from an ASP.NET Web Forms program or an ASP program.

 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 Web application. Let's use this simple program in this tutorial.

  Run Visual Studio 2008, select "File", "New" (see Figure 1), and use the MVC template to create an ASP.NET MVC program. In the "New Project" dialog box, select your preferred programming language in "Project Type (P)" (Visual Basic or C#), and select ASP.NET MVC Web Application under "Template". Click the "OK" button.

Understand models, views and controllers (C#, asp.net)

After creating a new ASP.NET MVC program, the Create Unit Test Project dialog box appears (see Figure 2). This dialog box will create a separate ASP for you in the solution to test your ASP. NET MVC program. Select the option No, do not create a unit test project and click the OK button.

Understand models, views and controllers (C#, asp.net)

Figure 2 Create unit test dialog box

 The ASP.NET MVC program is created. You will see several folders and files in the Solution Explorer window. In particular you will see three folders named Models, Views and Controllers. As the names suggest, these three folders contain files that implement models, views, and controllers.

 If you expand the Controllers folder, you will see a file named AccountController.cs and a file named HomeControllers.cs. Expand the Views folder and you will see three sub-folders named Account, Home and Shared. Expand the Home folder and you will see two files named About.aspx and Index.aspx (see Figure 3). These files make up the sample application including the default ASP.NET MVC template.

Understand models, views and controllers (C#, asp.net)

Select "Debug" and "Start Debugging" to run the sample program. Or you can press the F5 key.

When you run the ASP.NET program for the first time, the dialog box shown in Figure 4 will appear. It is recommended that you start debugging. Click the "OK" button and the program will run.

Understand models, views and controllers (C#, asp.net)

Figure 4 Debugging Not Started Dialog

When running an ASP.NET MVC program, Visual Studio will run your program in the browser. The sample program includes 2 pages: Index page and About page. When the program is started for the first time, the Index page appears (see Figure 5). You can navigate to the About page by clicking the menu link in the upper right corner of the program.

Understand models, views and controllers (C#, asp.net)

Pay attention to the URL in the browser address bar. When you click the About menu link, the URL in the address bar changes to /Home/About.

 Close the browser window and return to Visual Studio. You cannot find the file in the path Home/About. This file does not exist, how is this possible?

 A URL is not equal to a page

  When generating a traditional ASP.NEW Web form program or ASP program, a URL corresponds to a web page. If a request is made to the server for a page named SomePage.aspx, then it is best that there is such a page named SomePage.aspx on the disk. If the SomePage.aspx file does not exist, you will get an ugly 404 – Page Not Found error.

 On the contrary, when generating an ASP.NET MVC program, there is no correspondence between the URL you enter in the browser address and the file you want to find in the program. In the

 ASP.NET MVC program, a URL does not correspond to a page on disk but to a controller action.

 In traditional ASP.NET or ASP programs, browser requests are mapped to pages. In contrast, in an ASP.NET MVC application, browser requests are mapped to controller actions. ASP.NET Web Forms programs are content-centric. In contrast, ASP.NET MVC programs are centered around program logic.

 Understanding ASP.NET Routing

 The browser requests to obtain the mapping of the controller action through an ASP.NET framework feature called ASP.NET Routing. ASP.NET Routing is used by the ASP.NET MVC framework to route incoming controller action requests.

 ASP.NET Routing uses a routing table to handle incoming requests. This routing table is created when the web application is first run. It is created in the Global.asax file. The default MVC Global.asax file is shown in Listing 1.

 Code 1 – Global.asax

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 the ASP.NET program is started for the first time, the Application_Start() method will be called. In Code 1, this method calls the RegisterRoutes() method to create the default route table.

 The default routing table only includes one route. This default route breaks incoming requests into three segments (a URL segment is anything between two slashes). The first segment maps to the controller name, the second segment maps to the action name, and the last segment maps to a parameter called Id that is passed to the action.

 For example, consider the following URL:

  /Product/Details/3

 This URL is parsed to 3 parameters like this:

 Controller = Product

 Action = Details

 Id = 3

 Global.asax The default route defined in the 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 default values ​​in mind, think about how the following URL is parsed:

  /Employee

 This URL is parsed into three parameters like this:

 Controller = Employee

 Action = Index

 Id =

 Finally, if you open the ASP.NET MVC program without entering any URL (for example, http://localhost), the URL will be parsed like this:

 Controller = Home

 Action = Index

 Id =

 This request It is routed to the Index() action of the HomeController class.

Understanding Controllers

Controllers are responsible for controlling the way users interact with MVC programs. The controller contains the flow control logic for the ASP.NET MVC application. The controller determines what response is returned when the user sends a browser request. A controller is 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 contents of the HomeController.cs file are reproduced in Code 2.

 Code 2 – HomeController.cs

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();
        }
    }
}

Note that HomeController has two methods named Index() and About(). These two methods correspond to the two actions exposed by the controller. The URL /Home/Index calls the HomeController.Index() method and the URL/Home/About calls the HomeController.About() method.

Any public method in a controller is exposed as a controller action. You have to be especially careful about this. This means that people can call any public method in the controller simply by accessing the Internet and entering the correct URL into the browser.

Understanding Views

  Both the Index() and About() actions exposed by HomeController return a view. Views include HTML markup and content sent to the browser. A view is equivalent to a page in an ASP.NET MVC program. You have to create the view in the right place. HomeController.Index() action returns a view located at the following path:

  /Views/Home/Index.aspx

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

  /Views/Home/About.aspx

Normally, if you want to return a view for a controller action, then you need to create a subfolder under the Views folder with the same name as the controller. Within this subfolder, you will create an .aspx file with the same name as the controller action.

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

 Code 3 – About.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
 
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2 id="About">About</h2>
    <p>
        Put content here.
    </p>
</asp:Content>

如果你忽略代码3的第一行,视图的其余部分包含了标准的HTML。你可以输入任何你想要的HTML来修改视图的内容。

  视图和ASP或ASP.NET Web窗体中的页面很相似。视图可以包含HTML内容和脚本。你可以用你喜欢的编程语言写脚本(例如,C#或Visual Basic .NET)。使用脚本来显示动态内容,例如数据库数据。

 理解模型

  我们已经讨论了控制器和视图。最后一个话题就是模型了。什么是MVC模型?

  MVC 模型包含程序中的所有逻辑,而这些逻辑并不包含在视图或控制器中。模型应该包含所有程序业务逻辑,验证逻辑和数据库访问逻辑。例如,如果你用 Microsoft Entity Framework 来访问数据库,那么你要在Models文件夹中创建 Entity Framework 类 ( .edmx 文件) 。

  视图应该仅仅包含生成用户界面的逻辑。控制器应该仅仅包含返回正确视图的最小逻辑或者将用户重定向到其他action(流控制)。其它的任何事情都应该包含在模型中。

  通常,你应该为“胖”模型和“瘦”控制器而努力。控制器方法应该只包含几行代码。如果控制器action变得太“胖”的话,那么就应该考虑将逻辑挪出到Models文件夹中的一个新类中。

 总结

  这篇教程提供给你ASP.NET MVC Web程序不同部分的高度概览。你学到了 ASP.NET Routing 如何将传入的浏览器请求映射到特定的控制器action。你学到了控制器如何编配,视图如何返回到浏览器。最后,你学到了模型如何包含程序业务,验证和数据库访问逻辑。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools