Learning the basic concepts of ASP. NET MVC

Source: Internet
Author: User

Visual studio templates used to create mvc include an extremely simple mvc example by default. Through this example, you can understand the different components of the mvc application. Here we use this simple example to learn the basic concepts of ASP. net mvc.

Create an mvc application. Here we still do not select to add a test project.

After the creation is successful, you can see some folders and files. You need to pay special attention to the three folders Models, Views, and Controllers. As the name suggests, these three folders contain files in m, v, and c.

Expand the controllers folder. We can see a file named AccountController. cs and a HomeController. cs file. The accounts, Home, and Shared sub-folders are displayed in the Views folder. Expand the Home folder to see the two files, About. aspx and Index. aspx. These files constitute a simple mvc instance. The file structure is as follows:

 

Press F5 to run the project. If this is the first time you run the project, a dialog box is displayed. Select OK.

This simple project only contains two pages: Index and About. When the program runs for the first time, the browser displays the index page. You can navigate to the About page through the navigation on the upper right.

 

Note the address in the address bar. For example, when you click the About button, the address in the address bar changes to/Home/About.

Turn off the browser and return to VS. You will not find any files in the/Home/About directory. These files do not exist in this directory, but why?

ASP. net mvc basic concept: a URL is not equal to a page

When you create an asp program or asp.net web form program, a URL corresponds to a page one by one. If you request somepage. aspx from the server, there should be a page called somepage. aspx on the server disk. If somepage. aspx does not exist, you will receive a 404 error message.

However, in contrast to the mvc program, the addresses you write in the address bar do not exactly correspond to the files in the project. In the mvc program, a URL is equivalent to a controller action and is not An aspx page.

In traditional aspx programs, browser requests are mapped to pages. In mvc programs, browser requests are mapped to controller actions. Web forms applications are content-centric, and mvc applications are program logic-centric.

Learning the asp.net mvc path

The browser requests a controller action mapped by the asp.net routing Mechanism in the asp.net framework. Asp.net routing is used by the mvc Framework to select a path pointing to the controller action for incoming requests.

Asp.net routing uses a route Table) to submit the request. This route table is generated when the program runs for the first time. Route table is defined in the global. asax file. The default global. asax content is as follows:

 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.  
  8. namespace MvcApplication1  
  9. {  
  10.     // Note: For instructions on enabling IIS6 or IIS7 classic mode,   
  11.     // visit http://go.microsoft.com/?LinkId=9394801  
  12.  
  13.     public class MvcApplication : System.Web.HttpApplication  
  14.     {  
  15.         public static void RegisterRoutes(RouteCollection routes)  
  16.         {  
  17.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  18.  
  19.             routes.MapRoute(  
  20.                 "Default",                                              // Route name  
  21.                 "{controller}/{action}/{id}",                           // URL with parameters  
  22.                 new { controller = "Home", action = "Index", id = "" } // Parameter defaults  
  23.             );  
  24.  
  25.         }  
  26.  
  27.         protected void Application_Start()  
  28.         {  
  29.             RegisterRoutes(RouteTable.Routes);  
  30.         }  
  31.     }  
  32. }  

When the program runs, the Application_Start () method is called. In the code above, the Application_Start () method calls the RegisterRoutes () method and RegisterRoutes) to create the default route table.

The default route table consists of one route. This route divides an ongoing request into three parts. The URL in the first part is mapped to the controller, the URL in the second part is mapped to the action, and the last part is used to pass the parameter id to the action. For example

Assume the following url:/Product/Details/3

The url is divided into three parts: controller = product, action = details, id = 3

The default route defined in the global. asax file contains the default values of these three parameters. The default controller is Home, the default action is Index, and the default id is null. With the above knowledge as the basis, to analyze the following url

/Employee

It is divided into three parts: controller = employee, action = Index, and id = NULL.

Finally, if we open an mvc application and do not write any path such as http: // localhost), the path will be parsed into the following three parts:

Controller = Home, action = Index, id =.

The request is mapped to the Index in Homecontroller) action.

Learning ASP. net mvc: Understanding controllers

A controller is responsible for the interaction between a user and the mvc application. The controller contains the flow control logic of the mvc application. The controller determines what content is returned to the user after the user request.

Controller is just a class C # Or VB class). This simple mvc example contains a HomeController. cs file located in the controllers folder. The content is as follows:

 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.  
  7. namespace MvcApplication1.Controllers  
  8. {  
  9.     [HandleError]  
  10.     public class HomeController : Controller  
  11.     {  
  12.         public ActionResult Index()  
  13.         {  
  14.             ViewData["Title"] = "Home Page";  
  15.             ViewData["Message"] = "Welcome to ASP.NET MVC!";  
  16.  
  17.             return View();  
  18.         }  
  19.  
  20.         public ActionResult About()  
  21.         {  
  22.             ViewData["Title"] = "About Page";  
  23.  
  24.             return View();  
  25.         }  
  26.     }  
  27. }  

Note that the controller contains two methods: Index and About. These two methods are the two common actions provided by the controller. The/Home/Index path references the Index method in the controller. The same is true for About.

Any public method in the controller is treated as a controller action. Be very careful about this. This means that any public method under the controller can be accessed by a browser with the correct URL entered on the Internet.

Learning ASP. net mvc: understanding Views

The preceding two actions both return the view, which contains the html Tag and the content sent to the client browser. In mvc applications, view is equivalent to a page. You must create a view in a proper location. HomeController. Index () returns a view in The following directory: \ Views \ Home \ Index. aspx, The HomeController. About) and \ Views \ Home \ About. aspx.

Generally, if you want to return a view for a controller, you need to create a subdirectory under the Views directory with the same name as the controller. In this subdirectory, you must create An aspx page, and the same name as the controller action.

For example, the content of About. aspx is as follows:

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

If we ignore the first line, most of the remaining views are composed of standard HTML. We can modify this View using the HTML code we want.

View is very similar to asp and aspx web forms. It can include HTML and script content. You can write scripts c # Or VB based on your preferred. net language. Through these scripts, we can present dynamic data, such as database data.

Learning ASP. net mvc: Understanding Models

Controller and Views are all discussed. Finally, we will discuss the basic concept of ASP. net mvc: Models. What is mvc Models?

Models contains all the application logic that is not implemented in the controller and Views. Models should contain all application business logic, authentication logic, and data access logic. For example, if Microsoft Entity Framework is used for data access, you need to create a. edmx file of the Microsoft Entity Framework class under the Models folder.

View should only contain the logic related to the user interface. The controller should only contain the logic for converting to the correct View or to other actions. Everything else should be placed under Models.

Generally, we need to work toward "fat" Models and "thin" controllers. The controller method should contain only a few lines of code. If a controller is very fat, you need to consider moving the logic into a new class under the models folder.

  1. Introduction to ASP. net mvc Framework
  2. AsyncState parameter of ASP. NET
  3. ASP. net mvc executes asynchronous Action
  4. Overview ASP. net mvc Framework
  5. Use the UpdataModel method in ASP. NET MVC

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.