Introduction to ASP. NET MVC (top)

Source: Internet
Author: User
Tags ldap visual studio 2010

1. Mvc mode

The MVC pattern is a software architecture pattern. It divides the software system into three parts: model, view, and controller. The MVC pattern was first proposed by Trygve Reenskaug in 1974 and is a software design pattern invented by Xerox PARC in the 1980s for the programming language Smalltalk (Palo Alto). The purpose of the MVC pattern is to implement a dynamic program design that simplifies the subsequent modification and expansion of the program, and makes it possible to reuse a part of the program. In addition, this mode makes the program structure more intuitive by simplifying the complexity. By separating the basic parts of the software system, it also gives the functions of each basic part.

The model data model is used to encapsulate data related to the business logic of the application and how to handle the data. "Model" has the right to direct data access, such as access to the database. "Model" does not depend on "view" and "Controller", that is, the model does not care how it will be displayed or how it is manipulated. However, changes in the data in the model are generally advertised through a refresh mechanism. To implement this mechanism, the views that are used to monitor this model must be registered in advance on this model, so that the view can understand the changes that have occurred on the data model.

The view view layer is capable of achieving a purposeful display of data (in theory, this is not required). There is generally no logic on the program in the view. To implement the Refresh feature on the view, the view needs to access the data model it monitors, so it should be registered with the data it is monitoring beforehand.

Controller controllers play an organizational role across different levels to control the flow of applications. It handles the event and responds. An "event" includes the user's behavior and changes on the data model.

In the original JSP Web page, data-tier code such as database query statements and presentation layer code like HTML were mixed together. The more experienced developers separate the data from the presentation layer, but this is often not easy to do, and it requires careful planning and ongoing attempts. MVC essentially separates them from the ground. Although it takes some extra work to construct an MVC application, the benefits it brings to us are beyond doubt.

First, multiple views can share a model. Today, the same Web application provides a variety of user interfaces, such as the ability to send and receive e-mail through a browser, and to access the email via a mobile phone, which requires the Web site to provide both an Internet interface and a WAP interface. In MVC design mode, the model responds to user requests and returns response data, the view is responsible for formatting the data and presenting them to the user, business logic and presentation layer separation, the same model can be reused by different views, so greatly improve the reusability of the code.

Second, the controller is self-contained (self-contained) refers to the High independent cohesion of the object, and the model and view remain relatively independent, so it is convenient to change the application data layer and business rules. For example, porting a database from MySQL to Oracle, or transforming an RDBMS data source into an LDAP data source, simply change the controller. Once the controller is implemented correctly, the view displays them correctly, regardless of whether the data is from the database or the LDAP server. Since the three modules of the MVC pattern are independent of each other, changing one of them will not affect the other two, so it is possible to construct a good number of less-intrusive components based on this design idea.

In addition, the controller improves the flexibility and configuration of the application. Controllers can be used to connect different models and views to complete the user's needs, or to construct applications that provide a powerful tool. Given some reusable models and views, the controller can select the appropriate model models for the user's needs and then select the appropriate view to display the processing results to the user.

2. Hello World ASP. NET MVC 3

If you do not have a development environment, download Visual Studio 2010 and MVC3 here first. Create a new MVC3 project and select the Razor template engine. VS has already built a basic directory structure and two default pages.

Looking at the code for the file below, you can see that the class in controllers is dealing with some logical process and ultimately returns the view used to generate the page. The code in the model represents the data and some basic validation rules, and the view is populated with the data in the model. Run the next program and you can see a basic website. This is how the MVC site works:

1. When the first request is initiated from the client, the first execution is the Application_Start () method in Global.asax to do some initialization work, one of the important steps is the RegisterRoutes method, This method specifies how to map the URL to a specific method, as detailed later.

2. Generate an Routedata object from the mapping table specified in the first step and use this object to create a RequestContext object.

3. Mvcroutehandler creates a mvchandler and passes the RequestContext object to Mvchandler.

4. The Mvchandler object uses the RequestContext object to determine a Icontrollerfactory object to create a controller object.

5. The Mvchandler object invokes the Execute () method of the Controller object.

6. The controller's Controoleractioninvoker object determines which specific action method to invoke the controller.

7. The action method accepts the user parameter, executes the method, and returns an object of type result.

Right-click the Controller folder, create a new empty controller, name HelloWorld, and change the code to read as follows:

Public ClassHelloworldcontroller:controller
{
Public StringIndex ()
{
Return "Hello World";
}

Public string Hello ()
{
return hello everyone "}

public string Hello2 (string name)
{
return hello to " + name;
}
} /span>

You can see the corresponding string display by running the Web site and accessing/helloworld,/helloworld/hello,/helloworld/hello?name=jack in the browser separately. This example shows how a URL is mapped to a specific method. In general, instead of returning a string directly in the controller, we return a view, create a new Hellocontroller, do not modify the code, and access the/hello directly in the browser:

This is because we created a new controller but did not create the appropriate view,asp. NET will follow a certain path to find the view file. Right-click on the index method and select New view:

The following dialog box will then pop up:

Fill in the name of the view here, select the views engine, each view engine supports a view syntax, MVC3 supports a variety of template syntax, and can be extended by different view engines. The view engine that ASP. NET MVC used earlier is the same as the WebForm of ASP. The razor engine is a new engine for MVC3, and there are some open source engines that can be used, such as Ndjango, which implements the type Django template syntax. In this example, select the Razor engine. The bottom can choose a masterpage, this and WebForm master page concept is the same, using the default _viewstart page can be.

Write the next line of HTML code in the newly created view file:

@{
Viewbag.title = "Index";
}
<h2>Hello My first View</h2>

To run the Web site, visit the/hello page:

Where ViewBag is a dynamic type object that can be used to pass data between the controller and the page. Change the controller's code to:

public ActionResult Index ()
{
Viewbag.count = 4;
return View ();
}

The code for the view page changes to:

@{
Viewbag.title = "Index";
}

<H2>hello My first View </h2 >
<ul >
@for ( int i = 0; I < Viewbag {
<li >hello @i </li >
}
</ul >

Next, to achieve a basic function of adding and deleting. Suppose we want to manage the basic information of a movie, we first need to define a model type, create a new model, the code is as follows:

NamespaceHelloworld.models
{
Public ClassMovie
{
Public IntID {Get;Set; }
Public StringTitle {Get;Set; }
PublicDateTime ReleaseDate {Get;Set; }
Public StringGenre {Get;Set; }
public decimal price {getset}

public Class Moviedbcontext:dbcontext
{
public Dbset<movie>< Span style= "color: #000000;" > Movies {getset}
} /span>

Next, we create a new movie controller, using EntityFramework to access the data, the following configuration:

After clicking Add, you can see that a controller with basic functions has been built. In view, the corresponding Crud page is already available. We also need to configure the next database connection to add the connection string information in Web. config:

At this point the database and the movie table are not yet, but it doesn't matter, we use the Entity Framework 4 Code First development, it just needs an ordinary class to do, EF will help you to create the database and database tables work. Run the site with the following effects:

Open SQL Sever and you can see the movie table:

If the model file has changed, such as adding a field:

Public ClassMovie
{
Public IntID {Get;Set; }
Public StringTitle {Get;Set; }
PublicDateTime ReleaseDate {Get;Set; }
Publicstring Genre { get; set;}
public Decimal price { get; set;}
public string Rating { get; set;}
}

If you run the program again, an error will occur:

The error message says that the database has changed since the model was established, there are two ways to solve the problem, one is to call the Database.setinitializer method to rebuild the database automatically, and the other is to manually modify the database table. The first method, though simple, can cause existing data to be lost, and he rebuilds the entire database. However, it is very suitable for early development. First scenario is used here. The method is to create a new class in model that inherits from the Dropcreatedatabaseifmodelchanges class. The code in which you can add the optional initialization data is as follows:

UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.Data.Entity;

NamespaceHelloworld.models
{
Public ClassMovieinitializer:dropcreatedatabaseifmodelchanges<Moviedbcontext>
{
Protected Override voidSeed (Moviedbcontext context)
{
var movies= NewList<Movie>{
NewMovie {Title= "When Harry Met Sally",
ReleaseDate=DateTime.Parse ("1989-1-11"),
Genre="Romantic Comedy",
Rating="R",
Price=7.99M},
NewMovie {Title= "Ghostbusters",
ReleaseDate=DateTime.Parse ( "1984-3-13" Genre=comedy " Rating= "r ,
Price=8.99m},
};
Movies. ForEach (d => context. Movies.add (d));
}
}
}</moviedbcontext>

Then register this object in Global.asax:

protected void Application_Start ()
{
System.Data.Entity.Database.SetInitializer (new HelloWorld.Models.MovieInitializer ());
// remaining unchanged
}

To run the next program, you may encounter this error:

"This operation requires a connection to the ' master ' database. Unable to create a connection to the ' master ' database because the original database connection have been opened and Creden Tials has been removed from the connection string. Supply an unopened connection. "

I found a solution here. You need to add the persist Security info=true in the link string. Then the program will run normally. After running, the view page does not change automatically and needs to be modified manually. After the modification is complete, look at the edit page:

You can update the rating field at this time. The edit page also comes with a validation function, but in English, we will improve this verification feature below.

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.