1. MVC Mode
The MVC mode is a software architecture model. It divides a software system into three parts: model, view, and controller ). The MVC pattern was first proposed by Trygve reenskaug in 1974. It was a software design pattern invented by Xerox PARC in 1980s for the program language smalltalk. The purpose of the MVC pattern is to implement a dynamic program design, simplify subsequent modifications and extensions of the program, and make reuse of a part of the program possible. In addition, this mode simplifies the complexity to make the program structure more intuitive. The software system also gives the functions of each basic part through the separation of its basic parts.
Model is used to encapsulate data related to the application's business logic and to process the data. The "model" has the right to directly access data, such as accessing databases. "Model" does not depend on "View" and "controller", that is, the model does not care about how it is displayed or operated. However, data changes in the model are generally published through a refresh mechanism. To implement this mechanism, the views used to monitor this model must be registered on this model in advance, so that the views can understand the changes in the data model.
The view layer can display data purposefully (theoretically, this is not necessary ). Generally, there is no program logic in the view. To refresh a view, the view needs to access the data model it monitors. Therefore, you should register the data that it monitors in advance.
The Controller acts as an organizational unit between different layers and is used to control application processes. It processes events and responds. "Events" include user behaviors and changes in data models.
In the original JSP page, the data-Layer Code such as the database query statement is mixed with the presentation-Layer Code such as HTML. Experienced developers will separate the data from the presentation layer, but this is usually not easy. It requires careful planning and continuous attempts. MVC strictly separates them. Although constructing an MVC application requires some additional work, the benefits it brings us are beyond doubt.
First, multiple views can share one model. Today, the same web application provides a variety of user interfaces. For example, you want to be able to send and receive emails through a browser, or access your email through a mobile phone, this requires the web site to provide both the Internet interface and WAP interface. In the MVC design mode, the model responds to user requests and returns response data. The view is responsible for formatting and presenting the data to the user. The business logic is separated from the presentation layer, the same model can be reused by different views, which greatly improves code reusability.
Second, the controller is a self-contained object, which is highly independent from the model and view. Therefore, the data layer and business rules of the application can be easily changed. For example, to port a database from MySQL to Oracle or change the RDBMS data source to an LDAP data source, you only need to change the controller. Once the controller is correctly implemented, the view correctly displays the data from the database or the LDAP server. Because the three modules in the MVC mode are independent of each other, changing one of them will not affect the other two. Therefore, based on this design idea, we can build good components with little mutual interference.
In addition, the Controller improves application flexibility and configurability. Controllers can be used to connect different models and views to meet user needs. They can also build applications to provide powerful means. Given some reusable models and views, the controller can select an appropriate model for processing based on the user's needs, and then select an appropriate view to display the processing results to the user.
2. ASP. net mvc 3 for hello World
If no development environment is available, download Visual Studio 2010 and mvc3. create an mvc3 project and select the razor template engine. VS has created a basic directory structure and two default pages.
View the code of the file. You can see that the class in controllers is used to process some logic processes, and the view is returned to generate the page. The code in the model represents data and some basic verification rules. The view is filled with the data in the model. Run the program to view a basic website. The MVC website runs like this:
1. when the first request is initiated from the client, the first request is global. the application_start () method in asax to complete initialization. The important step is the registerroutes method. This method specifies how to map URLs to specific methods.
2. Generate a routedata object based on the ing table specified in step 1, and use this object to create a requestcontext object.
3. mvcroutehandler creates an mvchandler and passes the requestcontext object to mvchandler.
4. The mvchandler object uses the requestcontext object to determine an icontrollerfactory object to create a controller object.
5. The mvchandler object calls the execute () method of the controller object.
6. The Controller's controoleractioninvoker object determines which action method the Controller calls.
7. The action method accepts user parameters, executes the method, and returns an object of the result type.
Right-click the Controller folder, create an empty controller, name it helloworld, and change the code to the following:
Publicclass helloworldcontroller: Controller
{
Publicstring index ()
{
Return "Hello World ";
}
Publicstring Hello ()
{
Return "Hello everyone ";
}
Publicstring hello2 (string name)
{
Return "Hello to you" + name;
}
}
Run the website and access/helloworld,/helloworld/Hello,/helloworld/Hello respectively in the browser? Name = Jack. The corresponding string is displayed. This example shows how a URL is mapped to a specific method. Generally, we do not directly return a string in the controller, but return a view and create a new hellocontroller. without modifying the code, we can directly access/hello in the browser:
This is because the controller is created but the corresponding view is not created. ASP. NET searches for the View File according to a certain path. Right-click the index method and choose create view:
The following dialog box is displayed:
Enter the view name and select View engine. Each view engine supports one view syntax. mvc3 supports multiple template syntaxes and can be expanded using different view engines. ASP. net mvc previously used the same view engine as Asp.net's webform. The razor engine is a new engine added to mvc3, and some open-source engines can be used. For example, ndjango implements the template syntax of Django type. In this example, select the razor engine. You can select a masterpage at the bottom. This is the same as the master page of webform. You can use the default _ viewstart page.
Write a line of HTML code in the newly created View File:
@{
Viewbag. Title = "Index ";
}
<H2> hello my first view </H2>
Run the website and access the/Hello page:
Viewbag is a dynamic object that can be used to transmit data between the Controller and the page. Change the Controller code:
Public actionresult index ()
{
Viewbag. Count = 4;
Return view ();
}
The view page code is changed:
@{
Viewbag. Title = "Index ";
}
<H2> hello my first view </H2>
<Ul>
@ For (INT I = 0; I <viewbag. Count; I ++)
{
<Li> Hello @ I </LI>
}
</Ul>
Next, we will implement a basic addition, deletion, and modification function. Suppose we want to manage the basic information of a movie. First, we need to define a model type and create a model. The Code is as follows:
Namespace helloworld. Models
{
Publicclass movie
{
Publicint ID {Get; set ;}
Publicstring title {Get; set ;}
Public datetime releasedate {Get; set ;}
Publicstring genre {Get; set ;}
Publicdecimal price {Get; set ;}
}
Publicclass moviedbcontext: dbcontext
{
Public dbset <movie> movies {Get; set ;}
}
}
Next, we create a movie controller and use entityframework to access data. The following Configuration:
Click Add. You can see that a controller with basic functions has been created. In the view, the corresponding crud page is also available. We also need to configure the database connection and add the connection string information in Web. config:
At this time, the database and the movie table do not exist, but it does not matter. We use the code first development of Entity Framework 4, which only requires an ordinary class, EF will help you create databases and database tables. Run the website as follows:
Open SQL Sever and you can see the movie table:
If the model file changes, for example, a field is added:
Publicclass movie
{
Publicint ID {Get; set ;}
Publicstring title {Get; set ;}
Public datetime releasedate {Get; set ;}
Publicstring genre {Get; set ;}
Publicdecimal price {Get; set ;}
Publicstring rating {Get; set ;}
}
Then run the program, and an error will occur:
The error message prompts that the database has changed since the model was created. There are two solutions to solve this problem: first, the database. setinitializer method is called to automatically recreate the database, and second, the database table is manually modified. The first method is simple, but it will lead to the loss of existing data, and the whole database will be rebuilt. But it is very suitable for use at the early stage of development. The first solution is used here. The specific method is to create a new class in the model that inherits from the dropcreatedatabaseifmodelchanges class. You can add the optional initialization Data Code. The Code is as follows:
Using system;
Using system. Collections. Generic;
Using system. Data. entity;
Namespace helloworld. Models
{
Publicclass movieinitializer: dropcreatedatabaseifmodelchanges <moviedbcontext>
{
Protectedoverrisponid seed (moviedbcontext context)
{
VaR movies = new list <movie> {
New movie {Title = "When Harry Met Sally ",
Releasedate = datetime. parse ("1989-1-11 "),
Genre = "romantic comedy ",
Rating = "r ",
Price = 7.99 m },
New movie {Title = "Ghostbusters ",
Releasedate = datetime. parse ("1984-3-13 "),
Genre = "Comedy ",
Rating = "r ",
Price = 8.99 m },
};
Movies. foreach (D => context. Movies. Add (d ));
}
}
} </Moviedbcontext>
Register this object in global. asax:
Protectedvoid application_start ()
{
System. Data. entity. database. setinitializer (New helloworld. Models. movieinitializer ());
// The rest remain unchanged
}
If you run the program again, this error may occur:
"This operation requires a connection to the 'master' database. unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. supply an unopened connection."
I found the solution here. Add persist Security info = true in the Link string. Then the program runs normally. After running, the view page does not change automatically and needs to be modified manually. After the modification is complete, check the editing page:
In this case, you can update the rating field. The Edit page also comes with the verification function, which is only in English. We will improve the verification function below.