ASP. NET MVC Development Basics Learning Note (1): Go to MVC mode

Source: Internet
Author: User

First, ASP. Net of two development Modes 1.1 ASP. WebForm Development Mode

(1) Process flow

In the traditional WebForm mode, we request an example of http://www.aspnetmvc.com/blog/ Index.aspx URL, then our WebForm program will go to the root directory of the site to look for the index.aspx file under the blog directory, and then by the index.aspx page codebehind file (. CS file), which may include a database to fetch data (where the BLL is not discussed here), and then be presented to the user by the Index.aspx page.

In summary, in WebForm mode: a URL is requested on the server with the URL corresponding to the path of the physical file (aspx file or other), and then by the file to process the request and return the results to the client.

(2) Development methods • Server-side controls • General handlers +html static pages +ajax general handlers +html template engine

1.2 ASP. NET MVC development Model

(1) Process flow

in ASP. NET MVC, the URL requested by the client is mapped to the appropriate controller, then the controller handles the business logic, perhaps the data is taken from the model, and then the controller chooses the appropriate view to return to the client. And again back in front of our run ASP. http://www.aspnetmvc.com/home/index This URL, which is actually accessed by Home The action of the index in the controller.

(2) Notable features • The release of the first open source project in 2009, has been in the past 5 years, the development of a gradual improvement • More concise, closer to the original "request-processing-response" • More development, more new features, community active • will not replace the WebForm bottom and WebForm are the same, It's just a different treatment on the pipe.

Ii. two different interpretations of the MVC pattern

MVC pattern two kinds of comprehension: one is the expression pattern , the other is the schema pattern . It divides the application into three main components: view, controller, and model. Now, let's see what m-v-c stands for.

M: Model is primarily a component that stores or processes data, and the model actually implements the business logic layer for the corresponding database operations of the entity class, such as: CRUD. It includes application information such as data, validation rules, data access, and business logic. (Supplemental: ViewModel: View model) V: View is a user interface layer component. The main focus is to show the data in the model to the user. The ASPX and ascx files are used to handle the responsibilities of the view; C: The Controller handles user interaction, obtains data from the model and passes the data to the specified view; (1) MVC as an understanding of architectural patterns

As an architectural pattern, view is responsible for presenting the data, while the controller is responsible for acquiring the data that the view passes, and then invoking the business logic layer to process the completed data to the view for presentation. The model then processes the business logic and returns the results to the controller. From a traditional three-tier architecture, both view and controller belong to the UI layer, while model spans the BLL and DAL layers.

(2) MVC as an expression pattern of understanding

(3) MVC Schema Model synthesis model

As you can see, the difference between the two different understandings of MVC lies in the understanding of model: the model as a business model (BLL, DAL, etc.) or as a view model (ViewModel).

Third, WebForm vs MVC

(1) WebForm

Advantages: 1. Provide a large number of server-side controls, can achieve rapid development;

2.ViewState backhaul data is very convenient;

3. Low learning costs;

Disadvantages: 1. The encapsulation is too strong, although the study cost is low, many bottom things let the beginner not very understand;

2. The customization control is not flexible, not conducive to the work of art and development staff, often those server control processing a little careless will lead to error;

3. ViewState in the page will cause a lot of traffic consumption;

TIP: For more information about WebForm server controls and viewstate, a friend who doesn't know can read another blog post, "ASP. NET WebForm Learning Note: ASPX and server Control quest."

(2) MVC

Advantages: 1. It is easy to divide the complex application into model (ViewModel), View, controller three component models, the processing background logic code and foreground display logic are very good separation, belong to the loose coupling relationship, in the large project application, it is more easy to develop and test the development of agile, Have a strong scalability;

2. Because there is no server-side control, so the programmer control will be more flexible, the page is cleaner, no viewstate;

3. By modifying the routing rules, you can control the generation of custom URLs, so it is easier to control the generation of SEO-friendly URLs;

4. Strong-type view implementation, Razor view, model binding mechanism, model validation mechanism, more secure and efficient;

Disadvantages: High learning costs, complex structures, and unnecessary frequent access to unchanged data will also impair operational performance.

Iv. First ASP. NET MVC Program 4.1 file organization structure after new project

(1) Create a new ASP. NET MVC 4 project, select the basic configuration and the ASPX view engine (temporarily without the razor engine).

(2) vs the basic file organization structure we generated as shown in:

As you can see, the VS Default helps us create models, views, and controllers three folders, which make up our ASP. NET MVC pattern project. Where controllers is the class file for all controllers, and models is the class file for all models, and views is where all cshtml or ASPX files reside.

4.2 "convention greater than configuration" for the controller

Create a new controller in the controllers, named HomeController. Creates a new view in the default index action, which is the default name of index. (1) The controller is placed in the Controllers folder, and the naming method ends with a controller

(2) each controller corresponds to a folder in the View , the name of the folder is the same as the controller name (3) The method names in the controller correspond to a view view (not required, but recommended) and The name of the view is the same as the name of the action (4) The controller must be a non-static class, and to implement the IController Interface (5) The controller type can be placed in other projects

4.3 Related conventions for views

(1) All views must be placed in The View directory (2) different controller views are separated by folders, each controller corresponds to a view directory (3) General view name corresponds to the action of the Controller (not required) (4) Multiple controllers Public views are placed in shared: such as common error pages, list template pages, form template pages, and so on;

4.4 Data transfer bridge-viewdata and ViewBag

First, ViewData is a key/value-pair Dictionary collection data structure used to build a bridge between the controller and the view that transmits data. (1) ViewData is the controller's property, and This property is inherited Controllerbase .

(2) There is also an attribute of a viewdata under ViewPage

(3) When the Controller's action method executes, it returns Viewresult, and then the MVC framework executes the Excuteresult method, and the ViewData data in the controllers is passed to the ViewPage class, which is actually Assign the controller's ViewData value to the ViewData property of the ViewPage page . (4)viewbag Pass data: We assign the dynamic property of the ViewBag, the value is actually stored in the ViewData , the name of the dynamic property is saved as the key of the viewdatadictionary. The value of the dynamic property is stored as a value of viewdatadictionary.

PS: Viwebag is actually a viewdata that contains a layer of dynamic, with two brothers sharing a container.

(5) Comparison of ViewData and ViewBag

viewdata ViewBag
It is Key/value dictionary collection It is a dynamic type pair like
asp.net MVC3 only
based on the ASP. NET 4.0 and the. NET Framework
viewbag slower than ViewData
when querying data in ViewPage you need to convert the appropriate type
There are some type conversion codes Better readability

(6) How to use ViewData and ViewBag in the program

① the code in the controller

JavaPublic <textarea class="crayon-plain print-no" style="line-height: 15px !important; font-size: 13px !important; z-index: 0; opacity: 0; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; -webkit-tab-size: 4;" readonly="" data-settings="dblclick">ActionResult Index () {viewdata["Name"] = "Edison Chou"; Viewbag.name = "Edison Chou"; return View ();}</textarea>
123456 public actionresult Index() { ViewData["Name"] = "Edison Chou"; ViewBag. Name = "Edison Chou"; return View(); }

② code in view

XHTML <textarea class="crayon-plain print-no" style="line-height: 15px !important; font-size: 13px !important; z-index: 0; opacity: 0; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; -webkit-tab-size: 4;" readonly="" data-settings="dblclick"><body> <div> <p>hi,asp.net MVC first demo!</p> <% for (int i = 0; I < 5; i++) {Response.Write ("Hello world!<br/>"); }%> <p><%: viewdata["Name"]%></p> <p><%: Viewbag.name%></p> </div></body></textarea>
12345678910111213 <body> <div> hi,asp.net MVC First demo! <% For (int i = 0; I < 5; I+ +)             { Response. Write("Hello world!<br/>");             } %> <p><%: ViewData["Name"] %></p> <p><%: ViewBag. Name %></p> </div> </body>

4.5 Preliminary understanding of the routing mechanism

We can tell by debugging that all requests in MVC boil down to the action under the controller. Therefore, all requests are to specify a specific Action,url format that is based on the routing rules. So, what is the default for routing rules in ASP.

Java Public <textarea class="crayon-plain print-no" style="line-height: 15px !important; font-size: 13px !important; z-index: 0; opacity: 0; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; -webkit-tab-size: 4;" readonly="" data-settings="dblclick">class routeconfig{public static void RegisterRoutes (RouteCollection routes) {routes. Ignoreroute ("{resource}.axd/{*pathinfo}"); Routes. MapRoute (Name: "Default", url: "{controller}/{action}/{id}", Defaults:new { Controller = "Home", action = "Index", id = urlparameter.optional}); }}</textarea>
12345678910111213 public class routeconfig {Public static void registerroutes(routecollection routes) /c10>         { routes. Ignoreroute("{resource}.axd/{*pathinfo}"); routes. MapRoute( name: "Default", URL: "{controller}/{action}/{id}", defaults: new { controller = " Home " , action = "Index" , id = Urlparameter. Optional }             );        }}

Open the App_start folder, you can find routeconfig this class, look at Routeconfig This class method, you can know the original is registerroutes this method for our ASP. NET MVC project set the default routing rules: { Controller}/{action}/{id}, which means that we can access the project by HTTP://LOCALHOST/HOME/INDEX/1 this URL. If we want to change the default routing rule, for example, if we want to access the project with this url:http://localhost/home-index-1, we'll just change the default routing rule above to: {Controller}-{action}-{id}.

Reference articles

(1) Lulu Studio, "Introduction to ASP: 1-Introduction", http://www.cnblogs.com/QLeelulu/archive/2008/09/30/1302462.html

(2) Mullen, "Basic video tutorial for ASP. NET MVC", http://bbs.itcast.cn/thread-26722-1-1.html

(3) Mountains, "correct understanding of WebForm and ASP. NET MVC", http://www.cnblogs.com/wlb/archive/2009/12/07/1618954.html

(4) Zhaojunpeng, "ViewData and ViewBag", http://blog.segmentfault.com/zhaojunpeng/1190000000472818

ASP. NET MVC Development Basics Learning Note (1): Go to MVC mode

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.