Basic learning of MVC-theory

Source: Internet
Author: User

1. Introduction   ? Defined? What is MVC

The full name of MVC is the model View Controller, which is the abbreviation for the models-view-controller, a software design paradigm that organizes the code with a method of business logic, data, and interface display separation. Aggregating business logic into a single component does not require rewriting business logic while improving and personalizing the interface and user interaction. MVC is uniquely developed to map the traditional input, processing, and output functions in a logical graphical user interface structure.

    ? VC mode and our familiar WebForm mode

Look at these two pictures above, the above picture is the Web request mode, the following is the MVC pattern, we can see that the first Web-mode client sends a request to the browser: for example: www.itcast.cn/index.aspx; The browser sends a message request to the server, The server-side framework creates a Page object, processes the input data and outputs HTML or other content, and finally renders the processed data as HTML or JS or CSS back to the client browser for display. Traditional Web development is to enter a URL, the request is a Page class

The second way is the MVC approach, the same is to send requests to the server, such as Www.itcast.cn/news/index, unlike the traditional Web form, in the server framework, according to the routing configuration, the URL passed over to parse, create news object, The object's index method is called, the data is processed in the method, the result is stored in the view, and the result is rendered as HTML or JS or CSS in the form of a view returned to the client browser. and MVC is a method in the request page class and then the data is transferred to the view for display.

Look at these two diagrams more clearly:

Traditional Web Forms:


MVC pattern:


    2. Internal explanation      ? Access path to the program

As we can see from the above figure, in MVC, the requested URL of the client is mapped to the appropriate controller, and then the controller handles the business logic, perhaps taking the data from the model, The controller then chooses the appropriate view to return to the client.

to create a new small program: Create a new solution, and then add a controller with the following code:

<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong>using mvcblog.models;using system;using system.collections.generic;using System.Linq;using  System.web;using system.web.mvc;namespace mvcblog.controllers{//1. Controller Class (inherited controllers) public class HomeController:        Controller {//Create a data set (pseudo data) #region 0.1 initialize data set + void InitData ()//<summary> Initialize data collection///</summary> public list<models.dog> InitData () {List<mod Els. dog> list = new list<models.dog> () {new Dog () {id=1,name= "Sample ~ ~"}, new Dog () {Id=2,n            Ame= "Sample 2~~"}, New Dog () {id=3,name= "Sample 3~~"}, New Dog () {id=4,name= "Sample 4~~"}};        return list; } #endregion//2.action method (can be seen as model of MVC design pattern) public ActionResult Index () {//define a container, and design capacity System.Text.StringBuilder sbhtml = new System.teXt.            StringBuilder (4000);            2.1 Read the current business, such as reading a database, judging, etc.//2.1 create a data collection to get the current data list<models.dog> List = InitData (); 2.1.1 Iterates through the collection, generates HTML code, and deposits it into the sbhtml list.            ForEach (D + = {sbhtml.appendline ("<div>" + d.tostring () + "</div>");            }); Using ViewBag to pass data to a index.cshtml//viewbag with the same name is a collection of dynamic types that can dynamically add any type of property and value of any name viewbag.htmlstr = sbhtm            L.tostring ();        2.3 Loading the same name View index.cshtml return view (); }}}</strong></span>

after that, add a dog class in models, with the following code:

<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong>using system;using system.collections.generic;using system.linq;using System.Web;namespace mvcblog.models{public    class Dog    {public        int ID {get;set;}        public string Name {get; set;}        public override string ToString () {            return ' id= ' + this.id + ", name=" + this. Name;}}    } </strong></span>

On the index method, right-click the Add view, the code for the view is as follows:


<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong>@{    Layout = null;} <! DOCTYPE html>

Run directly: effects such as:


We see that either the address of the former or the address of the latter, the content is the same, which means that the http://localhost:9711/Home/index is accessed by default.


We notice that the URL of the address bar is Home/index, if you follow the WebForm pattern we said earlier, we should be able to find the home directory under the root of our project, and then the home directory has an Index file, But we are not able to find the home directory under the root directory. However, let us in the views directory to find the views/home/index.aspx file, we enter this address to run to see:


Why is this, the path is correct, but can not show, what is going on? Let's take a look at it.

      ? MVC operating mechanism Why does the input path appear to be correct but error?

Before we saw that even though the path entered was correct, it went wrong, what happened?

We open the Views folder of the configuration file, in fact, there is a configuration file under this folder,


This solves the reason why the previous direct access to the views/home/index.aspx file here, there will be a 404 error, said the file could not be found? because in MVC, it is not recommended to go directly to the view, so when we visit, that is, access to the views directory of all the files will be System.Web.HttpNotFoundHandler so we do not use the resource files (CSS, JS, pictures, etc. ) into the views directory.

Why did the first two inputs come out and the final result?

in MVC, the requested URL of the client is mapped to the appropriate controller, then the controller handles the business logic, perhaps taking the data from the model, and then the controller chooses the appropriate view to return to the client.

When we run the ASP. NET MVC program to access this URL, it actually accesses the action of index in HomeController.


So why the first address is also accessible ah, http://localhost:9711, because of the MVC routing mechanism, we look at the configuration of the route:


We can see here that a route named "Default" is defined, and the default parameters are defined. The meaning of the default parameter is that when we visit a URL such as http://localhost:9711, he will add the default parameter to the non-existent parameter, which is equivalent to accessing http://localhost:9711 /home/index The same. As a result, the two same results appear above.

    ? MVC Core Components

In the MVC design pattern, model refers to the business logic and data operations to be processed; View view is primarily about dealing with the user and showing it to the user; The controller is seen as a bridge between model and view.

The first controller is also the control

Many people are asking the model where, is not the establishment of the Models folder, in fact,/home/action method can be regarded as the model of MVC design pattern, Because this method operates based on the class or some data that is built into the models.

the second one is models .

Learned three layers may not be unfamiliar, three layer of the entity is this east, then they are the same? There are the same, there are differences, we can not only define entities, we can also build data model, that is EF (entityframework), also is ORM (Object Relational Mapping Framework/ Data persistence framework) An object-oriented operation framework for manipulating data in a data table based on an entity object, and the underlying invocation of ADO.

The third one is views

Requests sent by the client browser are returned to the client by the controller by selecting the appropriate view after the method index is processed by the controller. is mainly presented to the user to see.

3. Summary

Here is the understanding of their initial study, here is mainly about the theory, the next chapter will explain some applications and other knowledge. Please continue to follow ~



Basic learning of MVC-theory

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.