Asp.net MVC series (1): overview

Source: Internet
Author: User
What is the MVC mode ?. Asp.net MVC Framework is the MVC principle implemented

A Design Pattern of Model-View-controller in software engineering. (He is not just Asp.net MVC, but only one of his implementations.) His main design goal is to separate user interfaces from the logic layer (low coupling ), in this way, developers can better focus on the design and testing of the logic layer, so that the entireProgramHave a clear architecture.

MVC consists of three key parts: model, Controller, and view.

1) A model is composed of a lot of data and serves the logic layer but is independent of the logic layer. The model object knows all the data to be displayed, but does not know what the displayed object is. (I do not know whether the view is output as HTML or winform)

2) The view object is associated with the model. It is only responsible for object reality and some interface logic processing. The Controller is responsible for object processing and transmission.

3) The Controller object is used to associate the model and view objects. He knows both the data of the model object and the object to be displayed by the view object.

 

Comparison and Selection of Asp.net MVC and Asp.net webforms

Asp.net MVC is not used to replace Asp.net webforms, but to provide a new development mode for web development. You can choose a development mode suitable for yourself or your team.

Microsoft developed the ASP. net mvc framework based on the following objectives:

1) clear division of labor at each layer and testability (TDD supported)

2) A highly scalable plug-in architecture

3) more friendly URLs, easier Seo optimization, and support for rest.

4) You can continue to use some features of the original Asp.net.

5) for HTMLCodeFully controllable.

Advantages of ASP. net mvc:

1) the logic of Complex Systems is clearer. Because the layers of the M-V-C have been split.

2) developers have clearer goals and can focus more on their own development goals.

3) better support for TDD

4) Enhanced controllability of HTML.

5) more friendly URLs facilitate Seo

6) The generated HTML page is simpler and clearer, because no viewstate exists.

7) Support for JS frameworks by default

Advantages of ASP. NET webforms:

1) provides an event model for HTTP, which can be easily used by any developer.

2) provides a large number of standard controls and third-party controls to make development easier.

3) The viewstate mechanism is used to simplify state management.

So how should we choose the two during development?

TDD Control html Data-driver Like winforms Rad
MVC Yes Yes No No No
Webforms No No Yes Yes Yes

 

Of course, the above table is just a reference (O (∩ _ ∩) O ~)

Create an ASP. net mvc Project

1) First, download the ASP. net mvc Installation File and install it (. NET Framework SP1 is required ). After creating a web project, you can create an MVC project named myfirsymvcapplicatio, and choose to create a unit test project. The structure of the generated file is as follows:

First, let's take a look at the Global. asax. CS file:

Public class mvcapplication: system. web. httpapplication {public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} "); routes. maproute ("default", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "home ", action = "Index", id = ""} // parameter defaults);} protected void application_start () {registerroutes (routetable. routes );}}

 

Gobal. asax. the application_start () method in CS is triggered when each web program is started for the first time. It is important to implement the registerrouters (routecollection) method to register the route table. The parameter of the registerrouters method is the routecollection object. It is a newly introduced object in SP1 and a set of reasons. Its Two Methods ignoreroute and maproute are used here.

2) Next we will create a route (route name: employeeshow, Controller: employee, Action: Show, parameter: firstname ):

 
// Create employee route routes. maproute ("employeeshow", "Employee/{firstname}", new {controller = "employee", Action = "show", firstname = ""});
3) Now we create an employee class in the models folder as follows:
 
/// <Summary> /// employess domain model /// </Summary> public class employee {Public String firstname {Get; set;} Public String lastname {Get; set ;}public string email {Get; Set ;}}

 
4) Create an employee controller in the controllers file, delete the code in the class, and add a new show () method. The returned value is actionresult.
Public class employeecontroller: controller {// <summary> /// show a firstname /// </Summary> /// <returns> </returns> Public actionresult show (string firstname) {If (string. isnullorempty (firstname) {viewdata ["errormessage"] = "No firstname provider! ";}Else {employee Employee = new employee () {firstname = firstname, lastname =" exmaple ", email = firstname +" @ exmaple.com "}; viewdata ["firstname"] = employee. firstname; viewdata ["lastname"] = employee. lastname; view ["email"] = employee. email;} return view ();}}

 

(We can see that the controller we created inherits from sytem. Web. MVC. controller, and the returned object is actionresult, which are described later .)

5) Then we add a view corresponding to the show method of the controller.

<% @ Page title = "" Language = "C #" masterpagefile = "~ /Views/shared/site. master "inherits =" system. web. MVC. viewpage <myfirsymvcapplication. models. employee> "%> <asp: Content ID =" content1 "contentplaceholderid =" titlecontent "runat =" server "> show </ASP: content> <asp: content ID = "content2" contentplaceholderid = "maincontent" runat = "server"> <H2> show </H2> <% IF (viewdata ["errormessage"]! = NULL) {%> 
 
 controller 
Public actionresult show (string firstname) {employee Employee = NULL; If (string. isnullorempty (firstname) {viewdata ["errormessage"] = "No firstname provider! ";}Else {Employee = new employee () {firstname = firstname, lastname =" exmaple ", email = firstname +" @ exmaple.com "}; viewdata ["firstname"] = employee. firstname; viewdata ["lastname"] = employee. lastname; viewdata ["email"] = employee. email;} return view (employee );}

 

View:

<Asp: Content ID = "content2" contentplaceholderid = "maincontent" runat = "server"> <H2> show </H2> <% IF (viewdata ["errormessage"]! = NULL) {%>  

 

Next, enter http: // localhost: 6290/employee/tedyding to get a page.

6) Finally, let's look at the unit test code:

[Testmethod] public void show_acion_creates_employee_and_passes_to_view_when_firstname_is_specified () {// setup employee controller = new employee controller (); // execute viewresult result = controller. show ("tedyding") as viewresult; // Verity assert. isnotnull (result); viewdatadictionary viewdata = result. viewdata; assert. isnotnull (viewdata. model); assert. areequal ("tedyding", (viewdata. model as myfirsymvcapplication. models. employee ). firstname); assert. isnull (viewdata ["errormessage"]);} [testmethod] public void invoke () {// setup employeecontroller controller = new employeecontroller (); // execute viewresult result = controller. show (null) as viewresult; // Verity assert. isnotnull (result); viewdatadictionary viewdata = result. viewdata; assert. isnull (viewdata. model); assert. isnotnull (viewdata ["errormessage"]);}

 

So far, a simple MVC page is completed, that is, when we enter a name, a real prompt is provided; otherwise, an error prompt is provided.

Related Article

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.