Understanding models, views, and Controllers (C #)

Source: Internet
Author: User

This article gives you a high-level overview of the ASP. NET MVC model, views, and controls. In other words, explain the ' M ', ' V ', and ' C ' in ASP.

After reading this article, you should be able to understand how the different parts of ASP. NET MVC work together. And you should be able to understand how the ASP. NET MVC program differs from the ASP.

Sample ASP. NET MVC Application

The default Visual Studio template for creating an ASP. NET MVC Web program includes an extremely simple sample program that can be used to understand different parts of an ASP. NET MVC Web program. Let's use this simple program in this tutorial.

Run Visual Studio 2008, choose File, new (see Figure 1), and create an ASP. NET MVC program with the MVC template. In the New Project dialog box, select the programming language you prefer in project type (P) (Visual Basic or C #), and under Templates, select the ASP. NET MVC Web application . Click the "OK" button.


Figure 1 New Project dialog box

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


Figure 2 Creating a 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 respectively. As the name implies, 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 one 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 form a sample program that includes the default ASP. NET MVC template.


Figure 3 Solution Explorer window

Choose Debug, Start Debugging to run the sample program. Or you can press the F5 key.

When you run the ASP for the first time, the dialog box shown in Figure 4 appears, suggesting that you start debugging. Click on the "OK" button and the program will be up and running.


Figure 4 Debug not Started dialog box

When you run an ASP. NET MVC program, Visual Studio runs your program in the browser. The sample program consists of 2 pages: index page and about page. When the program 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 program.


Figure 5 Index Page

Note The URL of the browser address bar, and when you click the About menu link, the URL in the address bar becomes /home/about.

Close the browser window back to Visual Studio and you cannot find the path to the Home/about file. This file does not exist, how is this possible?

A URL is not equal to a single page

When you build a traditional asp.new Web Forms program or ASP program, a URL corresponds to a Web page. If a request is made to a page named Somepage.aspx on the server, it is best to have a page named Somepage.aspx on the disk. If the somepage.aspx file does not exist, an ugly 404–page not Found error will be obtained.

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

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

In a traditional ASP. NET or ASP program, the browser request is mapped to the page. Instead, in an ASP. NET MVC program, the browser request is mapped to the controller action. The ASP. NET Web Forms program is content-centric. Instead, the ASP. NET MVC program is centered on program logic.

Understanding ASP. Routing

The browser requests a mapping of the controller action through an ASP. NET Framework attribute called ASP. Routing. The ASP. NET Routing is used by the ASP. NET MVC framework to route requests for incoming controller action.

ASP. Routing uses a routing table to process incoming requests. This routing table is created the first time the Web program is run. It was created in the Global.asax file. The default MVC Global.asax file is shown in code 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 C Lassic mode,//visit Http://www.php.cn/public class MvcApplication:System.Web.HttpApplication {Publi c 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 =" Ind        Ex ", id =" "}//Parameter defaults);        } protected void Application_Start () {registerroutes (routetable.routes); }    }}

The Application_Start () method is called when the ASP. NET program starts for the first time. In code 1, this method calls the RegisterRoutes () method to create a default route table.

The default route table includes only one route. This default route divides incoming requests into three segments (one 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 section maps to a parameter named 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 the default values for all three parameters. The default controller is Home, the default Action is Index, and the default Id is an empty string. Thinking about these default values, think about the following URL is how to parse:

/employee

This URL is parsed into three parameters similar to this one:

Controller = Employee

Action = Index

Id =

Finally, if you open the ASP. NET MVC program if you do not enter any URLs (for example, http://www.php.cn/), the URL is parsed like this:

Controller = Home

Action = Index

Id =

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

Understanding the Controller

The controller is responsible for controlling how users interact with the MVC program. The controller includes the flow control logic of the ASP. 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 program includes a controller that is named HomeController.cs 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. mvc!";            return View ();        }        Public ActionResult on ()        {            viewdata["Title"] = "About page";            return View ();}}    }

Note HomeController has two methods, named Index () and about (): These two methods correspond to the two action exposed by the controller. Url/home/index calls the Homecontroller.index () method and Url/home/about calls the Homecontroller.about () method.

Any public method in the controller is exposed as the controller action. You should be very careful about this. This means that people can invoke any public method in the controller simply by accessing the Internet and entering the correct URL in the browser.

Understanding views

The two action of Index () and about () exposed by HomeController returns a view. Views include HTML markup and content sent to the browser. In an ASP. NET MVC program, the view is equivalent to a page. You must create the view in the right place. The Homecontroller.index () action returns a view at the following path:

/views/home/index.aspx

The Homecontroller.about () action returns a view at the following path:

/views/home/about.aspx

Typically, if you want to return a view for the controller action, you need to create a subfolder under the Views folder with the same name as the controller. Within this subfolder, you have to 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" >    

If you omit the first line of code 3, the rest of the view contains the standard HTML. You can enter any HTML you want to modify the contents of the view.

Views are similar to pages in ASP or ASP. NET Web Forms. Views can contain HTML content and scripts. You can write scripts in your preferred 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 the controller and the view. The last topic is the model. What is an MVC model?

The MVC model contains all the logic in the program, which is not included in the view or controller. The model should contain all program business logic, validation logic, and database access logic. For example, if you use the Microsoft Entity Framework to access a database, you create an Entity framework class (. edmx file) in the Models folder.

The view should contain only the logic that generated the user interface. The controller should simply include the minimum logic that returns the correct view or redirect the user to another action (flow control). Everything else should be included in the model.

In general, you should work hard for "fat" models and "thin" controllers. The Controller method should contain only a few lines of code. If the controller action becomes too "fat," then you should consider moving the logic out into a new class in the Models folder.

Summarize

This tutorial provides a high-level overview of the different parts of the ASP. NET MVC Web program. You learned how the ASP. NET Routing maps incoming browser requests to a specific controller action. You learned how the controller is allocated and how the view is returned to the browser. Finally, you learned how the model contains program business, validation, and database access logic.

The above is the understanding of the model, view and controller (C #) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.