Introduction to. NET MVC framework for. NET Web Development _ Practical Tips

Source: Internet
Author: User
Tags html form
MVC Concept

MVC is an architectural design pattern that applies primarily to graphical user interface (GUI) applications. So what is MVC? MVC consists of three parts: model, view (view), and controller (Controller).

Model is the application's data models. Data can be stored in a database, in a disk file, or even in memory, without any application. Model is the abstraction of these data, regardless of the storage form of data, the application can always use model to manipulate the data, without concern about the storage form of data. Data entity classes are commonly used as a model. For example, a customer management application uses a database to store customer data, a customer table in the database table customer, and the corresponding program typically establishes a data entity class customer to correspond to, this entity class even if the Customer table model.

View is the interface of the application. The user uses the view to manipulate the application and completes the interaction with the program. View provides a visual interface to display the data defined in model, where the user operates the data through the view and returns the results of the model data operation to the user. In a desktop application, view may be one or more Windows Forms. In a Web application, view is made up of a series of web pages, which is an. aspx page in the ASP.net web site.

Controller defines the application logic of the program. The user sends the action command to controller through the view, and the controller updates the model defined data according to the logic of the program design, and returns the operation result to the user through the view.

The history of MVC

The concept of MVC was first proposed by American professor Trygve Reenskaug in 1979. The 1988 MVC design pattern was formally presented in the book "A Cookbook for Using the" Model-view-controller User Interface Paradigm in Smalltalk-80. With the rapid development and popularization of Microsoft's Windows operating system, graphical user interface applications have gradually become mainstream, and many programming languages have an MVC framework to facilitate developers to design applications using this pattern. Most of these frameworks are for Web applications.

implementation of MVC design pattern in. NET Web Development

ASP.net 1.x uses codebehind technology to completely end the nightmare of traditional ASP program development: program logic is mixed with HTML interface elements. Codebehind technology will represent the. aspx file and logical (Controller) code for the Program Interface (View). The separation of Vb/.cs files is an MVC design. In ASP.net 2.0, the Codebeside technology is also available, that is, an. aspx file can have multiple. vb/.cs files, which facilitates further separation of the interface from the logical code.

March 2008 Microsoft released the MVC Framework (Preview 2 version) for ASP.net 3.5. This is a true sense of the ASP.net MVC framework. The framework can be described as a "subversion" of the way in which web-based form application development was previously familiar to developers. Change is "shocking":

1. Using URL routing technology: The URL of a Web program is no longer pointing to a specific physical page. aspx, but rather a method that points to a controller. A typical MVC architecture program, its URL might look like this:

Http://www.mysite.com/Customer/Index

A program that uses the MVC schema does not have to have a file name extension for its URL. The customer in the above URL is the name of controller. And index is a method name defined by the customer.

2. Web application interface. aspx no longer uses the server-side form:

<asp:form runat= "Server" ></form>

Then the postback associated with the server-side form and the page lifecycle events do not exist.

3. The page no longer has view state. You will not be able to use view state to store program status information under MVC.

4. Server control events that depend on the server-side form are no longer available, and the button_clicked events that developers are familiar with will no longer be needed under MVC.

NET MVC Example

After asp.net mvc Preview 2 is installed, a new project template, asp.net mvc Web application, is added in VS2008, as shown in the following illustration



After the project is created, the VS2008 automatically generates the project's file structure as follows, and the MVC three components each have a folder to store their own program files.

The URL routing mentioned earlier is set in Global.asax.cs:

Copy Code code as follows:

public class GlobalApplication:System.Web.HttpApplication
{
public static void RegisterRoutes (RouteCollection routes)
{
Note: The following versions of IIS need to be formatted with the URL format "{Controller}.mvc/{action}/{id}" to enable IIS7

Routes. ADD (New Route ("{controller}.mvc/{action}/{id}", New Mvcroutehandler ())
{
Defaults = new RouteValueDictionary (New {action = "Index", id = ""}),
);//Set URL routing format

Routes. ADD (New Route ("Default.aspx", New Mvcroutehandler ())
{
Defaults = new RouteValueDictionary (New {controller = "Customer", action = "Index", id = ""}),
)//Set the default URL to point to the Customer Controller index method
}

protected void Application_Start (object sender, EventArgs e)
{
RegisterRoutes (routetable.routes);
}
}

"Code 1": Global.asax.cs

Here's how to implement customer model, controller, and view:

Model: In the project's model folder, create a new LINQ to SQL Classes that drags the Customer table in the Northwind database to its Design view. This completes the customer corresponding model. As shown in Figure 4

Controller: Under the Controller folder in the project, create a new "MVC Controller Class" named CustomerContoller.cs. Add a public method index in this class, which is the method mapped for the default URL set in Global.asax.cs.

Copy Code code as follows:

public class Customercontroller:controller
{
public void Index (string id)
{
Northwind.Models.NorthwindDataContext dc = new Northwind.Models.NorthwindDataContext ();
Ilist<northwind.models.customer> Customers = DC. Customers.take (10). ToList ()//Fetch 10 customer records in the database
Renderview ("index", customers);/Return to Index View
}
}


"Code 2": CustomerController.cs

View: The code for the index method above indicates that after the Customercontoller index method executes, you need to return a view called Index to render the data to the user. Next, add the index view: In the project's view file, create a new subfolder of the customer. The view that is related to the customer controller is saved under this folder. Create a new "MVC View Class" and name it index.aspx. In the previous renderview ("Index", customers) method, the customers parameter is the data that controller is required to pass to the view, which is of type ilist< Northwind.models.customer>. To facilitate the use of this strongly typed data in view, View.aspx.cs uses the following code: note the bold part

Copy Code code as follows:

public partial class Index:viewpage<ilist<northwind.models.customer>>
{
}


"Code 3": Index.aspx.cs

The view.aspx code is as follows: ViewData the type of this member variable and the ilist<northwind.models.customer> type mentioned above.


Copy Code code as follows:

<%@ Page language= "C #" autoeventwireup= "true" codebehind= "Edit.aspx.cs" inherits= "Northwind.Views.Customer.Edit" %>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<div>
<table>
<tr>
<td>Edit</td>
<td>customer ID </td>
<td>company Name </td>
<td>contact Name </td>
<td>contact Title </td>
</tr>
<% foreach (Northwind.Models.Customer Customer in ViewData)
{%>
<tr>
<td><a href= "customer.mvc/edit/<%= Customer. CustomerID%> ">edit</a></td><!-url the Edit method pointing to the customer Contoller-->
<td></td>
<td> <%= customer. CustomerID%></td>
<td> <%= Customer.companyname%></td>
<td> <%= customer. ContactName%></td>
<td><%= customer. ContactTitle%></td>

</tr>
<%}%>
</table>
</div>
</body>

"Code 4": index.aspx

Here's how to implement the Customer controller edit method. Add the following code to the CustomerController.cs:

Copy Code code as follows:

public void Edit (string id)
{
Northwind.Models.NorthwindDataContext dc = new Northwind.Models.NorthwindDataContext ();
Customer C = DC. Customers.single (cus => cus. CustomerID = = ID);//Remove a customer record from the database that corresponds to the parameter ID

Renderview ("edit", c);/return Edit View


"Code 5": The Edit method in CustomerController.cs

Add the Edit View edit.aspx to the view/customer/folder in the project:

Copy Code code as follows:

public partial class Edit:viewpage<northwind.models.customer>
{
}


"Code 6": Edit.aspx.cs

Copy Code code as follows:

<%@ Page language= "C #" autoeventwireup= "true" codebehind= "Edit.aspx.cs" inherits= "Northwind.Views.Customer.Edit" %>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<!-The following HTML form submits the user's input to the customer Contoller Update method-->
<%using (html.form<northwind.controllers.customercontroller>) (CC=&GT;CC. Update (Viewdata.customerid)) {%>
<div>
Customer ID: <%= viewdata.customerid%> <br/>
Company Nmae: <%= html.textbox ("Customer.companyname", viewdata.companyname)%> <br/>
Contact Name: <%= html.textbox ("Customer.contactname", Viewdata.contactname)%><br/>
Contact Title: <%= html.textbox ("Customer.contacttitle", Viewdata.contacttitle)%>
</div>
<%= Html.submitbutton ("Save")%>
<%}%>
</body>


"Code 7": Edit.aspx

One of the Help class HTML in the MVC framework is used in code 7. This class can produce commonly used interface elements in view, such as HTML form, text input box, and so on.

Here's how to implement the Customercontroller Update method:

Copy Code code as follows:

public void Update (string id)
{
Northwind.Models.NorthwindDataContext dc = new NorthwindDataContext ();
Remove a customer record from the database that corresponds to the parameter ID:
Customer cust = DC. Customers.single (c => c.customerid = ID);
Assign a user's changes in edit view to the Cust object:
Bindinghelperextensions.updatefrom (Cust, Request.Form);
dc. SubmitChanges ();
Redirecttoaction ("index");//jump to index View
}


"Code 8": The Update method in CustomerController.cs

The code above implements the customer's list, edit, and update function through the ASP.net MVC framework, which shows that MVC separates the "graceful" of the application's model, view, and controller, and truly realizes a high cohesion, low coupling flexible architecture, Greatly reduce the complexity of the program, improve scalability and reusability. The impact of this framework on web development is not just a technical change, more is the change of Web program design idea--the Web program is no longer a collection of some column function pages, but a collection of functional units that are controller controlled, and the Web program is more like a set of "API" that is opened to the outside by its URL "。

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.