Table of Contents
Sample ASP.NET MVC Application
A URL is not equal to a page
Understanding ASP.NET Routing
Understanding Controllers
Understanding the view
Understanding the Model
Summary
Home Backend Development C#.Net Tutorial Understanding Models, Views and Controllers (C#)

Understanding Models, Views and Controllers (C#)

Feb 22, 2017 am 10:29 AM

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 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.


Figure 1 New Project Dialog Box

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 project for you in the solution to test your ASP.NET MVC application. Select the option No, do not create a unit test project and click the OK button.


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 subfolders 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.


Figure 3 Solution Explorer Window

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

When you run an 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.


Figure 4 Debugging Not Started Dialog Box

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.


Figure 5 Index page

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 as the browser address and the file you want to find in the program. In

 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 request obtains 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://www.php.cn/

    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);
        }
    }
}
Copy after login

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 into 3 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 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 do not enter any URL (for example, http://www.php.cn/), open ASP For a .NET MVC program, the URL is parsed like this:

Controller = Home

Action = Index

Id =

This request is routed to HomeController In the Index() action of the 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();
        }
    }
}
Copy after login

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 the view

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

Usually, 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>About</h2>
    <p>
        Put content here.
    </p>
</asp:Content>
Copy after login

If you ignore the first line of Code 3, the rest of the view contains standard HTML. You can enter any HTML you want to modify the content of the view.

Views are very similar to pages in ASP or ASP.NET Web Forms. Views can contain HTML content and scripts. You can write scripts in your favorite programming language (for example, C# or Visual Basic .NET). Use scripts to display dynamic content, such as database data.

Understanding the Model

We have discussed controllers and views. The last topic is models. What is the MVC model?

 MVC model contains all the logic in the program, which is not contained in the view or controller. The model should contain all program business logic, validation logic and database access logic. For example, if you use Microsoft Entity Framework to access the database, then you would create Entity Framework classes (.edmx files) in the Models folder.

The view should only contain the logic to generate the user interface. Controllers should only contain minimal logic to return the correct view or redirect the user to other actions (flow control). Everything else should be included in the model.

Generally, you should strive for "fat" models and "thin" controllers. Controller methods should only contain a few lines of code. If the controller action becomes too "fat", then you should consider moving the logic out to a new class in the Models folder.

Summary

This tutorial provides 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 specific controller actions. You learned how controllers are orchestrated and views returned to the browser. Finally, you learned how models contain programmatic business, validation, and database access logic.

The above is the content of understanding the model, view and controller (C#). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The world's most powerful open source MoE model is here, with Chinese capabilities comparable to GPT-4, and the price is only nearly one percent of GPT-4-Turbo The world's most powerful open source MoE model is here, with Chinese capabilities comparable to GPT-4, and the price is only nearly one percent of GPT-4-Turbo May 07, 2024 pm 04:13 PM

Imagine an artificial intelligence model that not only has the ability to surpass traditional computing, but also achieves more efficient performance at a lower cost. This is not science fiction, DeepSeek-V2[1], the world’s most powerful open source MoE model is here. DeepSeek-V2 is a powerful mixture of experts (MoE) language model with the characteristics of economical training and efficient inference. It consists of 236B parameters, 21B of which are used to activate each marker. Compared with DeepSeek67B, DeepSeek-V2 has stronger performance, while saving 42.5% of training costs, reducing KV cache by 93.3%, and increasing the maximum generation throughput to 5.76 times. DeepSeek is a company exploring general artificial intelligence

AI subverts mathematical research! Fields Medal winner and Chinese-American mathematician led 11 top-ranked papers | Liked by Terence Tao AI subverts mathematical research! Fields Medal winner and Chinese-American mathematician led 11 top-ranked papers | Liked by Terence Tao Apr 09, 2024 am 11:52 AM

AI is indeed changing mathematics. Recently, Tao Zhexuan, who has been paying close attention to this issue, forwarded the latest issue of "Bulletin of the American Mathematical Society" (Bulletin of the American Mathematical Society). Focusing on the topic "Will machines change mathematics?", many mathematicians expressed their opinions. The whole process was full of sparks, hardcore and exciting. The author has a strong lineup, including Fields Medal winner Akshay Venkatesh, Chinese mathematician Zheng Lejun, NYU computer scientist Ernest Davis and many other well-known scholars in the industry. The world of AI has changed dramatically. You know, many of these articles were submitted a year ago.

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Hello, electric Atlas! Boston Dynamics robot comes back to life, 180-degree weird moves scare Musk Hello, electric Atlas! Boston Dynamics robot comes back to life, 180-degree weird moves scare Musk Apr 18, 2024 pm 07:58 PM

Boston Dynamics Atlas officially enters the era of electric robots! Yesterday, the hydraulic Atlas just "tearfully" withdrew from the stage of history. Today, Boston Dynamics announced that the electric Atlas is on the job. It seems that in the field of commercial humanoid robots, Boston Dynamics is determined to compete with Tesla. After the new video was released, it had already been viewed by more than one million people in just ten hours. The old people leave and new roles appear. This is a historical necessity. There is no doubt that this year is the explosive year of humanoid robots. Netizens commented: The advancement of robots has made this year's opening ceremony look like a human, and the degree of freedom is far greater than that of humans. But is this really not a horror movie? At the beginning of the video, Atlas is lying calmly on the ground, seemingly on his back. What follows is jaw-dropping

KAN, which replaces MLP, has been extended to convolution by open source projects KAN, which replaces MLP, has been extended to convolution by open source projects Jun 01, 2024 pm 10:03 PM

Earlier this month, researchers from MIT and other institutions proposed a very promising alternative to MLP - KAN. KAN outperforms MLP in terms of accuracy and interpretability. And it can outperform MLP running with a larger number of parameters with a very small number of parameters. For example, the authors stated that they used KAN to reproduce DeepMind's results with a smaller network and a higher degree of automation. Specifically, DeepMind's MLP has about 300,000 parameters, while KAN only has about 200 parameters. KAN has a strong mathematical foundation like MLP. MLP is based on the universal approximation theorem, while KAN is based on the Kolmogorov-Arnold representation theorem. As shown in the figure below, KAN has

FisheyeDetNet: the first target detection algorithm based on fisheye camera FisheyeDetNet: the first target detection algorithm based on fisheye camera Apr 26, 2024 am 11:37 AM

Target detection is a relatively mature problem in autonomous driving systems, among which pedestrian detection is one of the earliest algorithms to be deployed. Very comprehensive research has been carried out in most papers. However, distance perception using fisheye cameras for surround view is relatively less studied. Due to large radial distortion, standard bounding box representation is difficult to implement in fisheye cameras. To alleviate the above description, we explore extended bounding box, ellipse, and general polygon designs into polar/angular representations and define an instance segmentation mIOU metric to analyze these representations. The proposed model fisheyeDetNet with polygonal shape outperforms other models and simultaneously achieves 49.5% mAP on the Valeo fisheye camera dataset for autonomous driving

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! Mar 21, 2024 pm 05:21 PM

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

See all articles