Reproduced ASP (i)--deep understanding of ASP. NET MVC

Source: Internet
Author: User

personally think that written more thorough ASP. NET MVC article, so reproduced over, the original link in the last:ASP. NET vs MVC vs WebForms

Many of the ASP. NET developers are beginning to touch MVC and think that MVC has nothing to do with ASP. NET is a new web development, in fact, ASP. NET is a framework for creating Web applications, and MVC is a more advanced architecture that enables better ways to organize and manage code, so it can be called an ASP. Mvc.

We can call the original ASP. ASP. NET Webforms, and the new MVC is called ASP.

ASP. NET Web Form

For the last 12 years, ASP has been serving and successfully developing Web applications. Let's start by understanding why ASP. NET is so popular and successfully applied.

The Microsoft programming language has become popular and widely used from the beginning of VB, and it is the result of the powerful Visual Studio that provides visual programming to enable rapid development.

With VS, developers can drag and drop UI elements and automatically generate code for those interfaces in the background. Called Background code. In the background code, developers can add logical code to manipulate these UI elements.

Therefore, Microsoft's visual RAD Architecture system has two components, on the one hand is the UI, on the one hand is the background code. Therefore, the ASP. NET Web forms, including ASPX and ASPX.CS,WPF, contain Xaml/xaml. CS and so on.

Problems with ASP. NET Web Formthe question we have to consider is, since the ASP. NET Web Form is so successful and has the advantage, why does Microsoft want to launch ASP. Mainly because of the performance problem of ASP. To define performance in a Web application in two ways:1. Response Time: Time consuming for server response requests2. Bandwidth consumption: How much data can be transmitted at the same time. Response Timewe can understand why the ASP. NET WebForm is slow and we do some small load tests. Using ASP. NET MVC and ASP. NET Webform, the response time of ASP is found to be twice times faster than Webform. and then we're thinking about a question. Why is ASP. NET MVC performance better? Take a look at the following example, a simple UI code and a background code for the UI. If a TextBox's aspx page:
<IDRunat= "Server">   
the corresponding UI background code:
   1:  void Page_Load (object sender, EventArgs e) 
   2:  {      
   3:        "make it Simple";            
   4:        textbox1.backcolor = Color.aqua;
   5:  }
Operation Result:If you look at the HTML output, the following code is displayed:
<nametypevalueIDstyle/>     
Let's think about the questions that are mentioned above.1. Is this HTML generation very effective? Are we consuming servers for a long time to get such simple HTML2. Can developers write HTML directly? Is it difficult to achieve?

from the analysis we can tell that each request has a conversion logic, run and convert the server control to HTML output. If our pages use complex controls, such as tables, tree controls, the conversion can become very bad and complex. The HTML output is also very complex. The response time is increased due to these unnecessary conversions. the solution to this problem is to get rid of the background code, written in plain HTML code. Bandwidth ConsumptionASP. NET developers are very familiar with viewstates because it is able to automatically save the status returned by the post, reducing development time. However, this reduction in development time is a huge drain and viewstate increases the size of the page. In the load test done, we found that ViewState added twice times more page storage compared to MVC. Here are the test results:

the increase in page size is due to the extra bytes generated by viewstate. is the viewstate. Many people may disagree with this view, but it is well known how developers work and, if there is a choice, they will certainly take other choices.

    1. HTML consumption
Now that we are all working behind the scenes and the ASP. NET Web server controls, there is no better way to get HTML and how to make them more effective. Can you determine what kind of HTML code will be generated, as shown in the ASPX code below?

    • <asp:label id="Label1" runat="server" text="I am Label" >

    •   
      <asp:literal id="Literal1" runat="server" text="I am a Literal" >
    • <asp:panel id="Panel1" runat="Server" >i am a panel

Does the lable tag generate div tags or span tags? The results of the HTML code generated after the run are as follows: Label generated the span tag, literal generated the conversion for simple text, and the panel was converted to a DIV tag.

<span id= "Label1">i am label</span>i am a literal

    • I am a panel

As a result, it is better to write HTML code directly and implement HTML controls than to generate HTML code.

So the solution to this problem is to write HTML code directly without using server controls.

The advantage of writing HTML code directly is that Web designers can work with developers to communicate in a timely manner. Designers can use their favorite design tools to design HTML code, like Dream Weaver, front page, etc., designed independently. If we use server controls, these designer tools may not be recognized.

2. Reuse of background code classesIf you look closely at some of the professional ASP. NET WebForm projects, you will find that the background code classes often contain a lot of code, and the code is very complex. Now, the background code class inherits the "System.Web.UI.Page" class. But these classes are not as reusable and instantiated as normal classes. In other words, it is never possible to execute the following code in the Weform class:1:webform1 obj = new WebForm1 (); obj. Button1_Click ();

    •  3. Unit Testing

Since the background code class cannot be instantiated, unit testing is also very difficult and cannot perform automated testing. Must be tested manually.

    • Solution Solutions

Now that you've talked about the two major problems with ASP. WebForm is server control and background code, here is the root diagram,

So what's the solution?

Is that we need to migrate the backend code to a separate, simple class library, and come to the ASP. NET server control and write some HTML examples.

ASP. NET Webform and MVC comparisons, such as:

How does Microsoft ASP. NET MVC compensate for problems with Web form?

Background code and server controls are the root cause of all problems. So if you look at the current WebForm architecture, the developer is using a 3-tier architecture. The three-tier architecture is composed of the ASPX and CS background code that is contained by the UI.

UI, business logic, and the middle tier containing data access

ASP. NET MVC consists of three parts, Model,view,controller. The controller contains background code logic, view is aspx, such as pure HTML code, model is the middle tier. These three parts can be obtained through the relationship.

So we will find that there are two changes in MVC, the view becomes simple HTML, the background code is moved to simple. NET class, called the controller.

The following are common steps for the ASP. NET MVC Request Flow:

Step 1: Get the controller first.

Step 2: The dependent behavior controller creates the model object, and the model invokes the data access layer through the transformation.

Step 3: After the data is populated with the model, it is passed to the view display layer for display purposes.

Here we have a look at the various components of ASP. Let's do some small experiments to get an insight into the various components of MVC. First we start with the controller controllers because the controller is a core part of the MVC architecture.

Do you really understand the controller of ASP.

In order for us to better understand the controller, we first need to understand the professional terminology involved in the controller: User interaction logic.

What is user interaction logic?

Scenario 1

Do you want to see what happens when the user enters the URL and presses the ENTER key?

The browser first needs to send a request to the server and the server responds again.

After these requests, the client is attempting to interact with the server, and the server responds with feedback because there are some judgment logic on the server side to handle the requests. These business logic that handles user requests and user interactions is called user interaction logic.

Scenario 2

In a common case, a request sent by the server is an HTML request. An HTML request consists of a set of input controls and a submit button.

What happens when the user clicks the "Save" button?

If your answer is that there are some event handlers to handle the button click event, then I'm sorry the answer is wrong.

There is no concept of events in Web programming, and ASP. NET Web Forms automatically adds processing code based on our behavior, so the illusion that we have is event-driven programming. This is just an abstract description.

When the button is clicked, a simple HTTP request is sent to the server. The difference is that the content entered in customer name,address and age is sent along with the request. Finally, if there is a request, the server side has the corresponding logic, so that the server can better respond to the request. In simple terms, the user interaction logic is written on the server side.

In ASP. C represents the controller, which is used to handle the user interaction logic.

Experiment one: Simple MVC Hello World, with a focus on controller.
    • Step1 creating an ASP. NET MVC 5 Project

Open the new project, "File", Visual Studio 2013.

    • Step 1.2 Select the Web app, enter the project name, select the storage path, and click OK.

    • Step 1.3 Select the MVC template

    • Step 1.4 Select Change Authentication (changes authorization), Pop-up dialog box select "No Authentication" and click OK.

    • Step to create a controller
    • Step 2.1, in Explorer, right-click the Controller folder and select Add->controller (Controller)

    • Step 2.2 Select the empty MVC 5 Controller and click Add

    • Step 2.3 Enter the name of the controller "TestController" and click Add.

In this step, it is important to note that the "Controller" keyword in the name must not be deleted. The name must contain the Controller keyword.

    • Step 3. Create a Behavior method

Open the newly created TestController class, you can discover the generated index method, delete the method, and add a new method named GetString, with the following code:

   1:  class Testcontroller:controller
   2:  {
   3:      
   4:     {        
   5:   
   6:    }
   7:  }
    • Step 4. Run and Test press the F5 key, enter in the address bar as "controllername/actionname", you need to be aware of the input controller name, you cannot enter "controller" only enter "Test".

Experiment One: Q&a

1. What is the relationship between TestController and test?

TestController is the class name, and test is the name of the controller, note that when you enter the name of the controller in the URL, you do not need to enter the controller word.

2. What is the action (behavior) method?

The Action method is simply a method of a controller's built-in public type, capable of receiving and processing a user's request, in the above example, the GetString method returns a string-type response.

Note: The default return request is HTML in ASP. If you need to return other types of requests, you must create an HTTP processor to override the content type. These operations are difficult in ASP. in ASP. NET MVC is very simple. If the return type is "String" returned directly, you do not need to send the full HTML.

3. What happens if an object value is returned from the action method?

Please browse the following code

   1:  namespace Webapplication1.controllers
   2:  {
   3:      class Customer
   4:      {
   5:          string CustomerName {get; set;}
   6:          string Address {get; set;}
   7:      }
   8:      class Testcontroller:controller
   9:      {
  Ten: Public          Customer GetCustomer ()
  One:          {
  :              new Customer ();
  :              "Customer 1";
  :              "Address1";
  :              return C;
  :          }
  :      }
  :  }

The output results are as follows:

When an object of similar type such as "Customer" is returned, the ToString () method is called, returning the class name in the form "Namespace.ClassName".

4. What do I do if I need to get the attribute value from the above example?

The "ToString" method of the simple rewrite class is as follows:

   1:  string ToString ()
   2:  {
   3: This       . customername+"|" + This. Address;  
   4:  }

Operation Result:

5. Is the Action method only decorated with the public modifier?

The answer is yes, and each public method is automatically called the action method.

6. What is the non-public method?

The methods of the class are relatively simple and are not publicly available. cannot be called in the web.

7. What if we need other functions to accomplish some specific functionality, but not how do I do it?

Use the Nonaction property decoration as follows:

   1:  
   2:  string Simplemethod ()
   3:  
   4:     "Hi, I am not action method";
   5:  }

When you try to send a request to the action method above, you get the following results:

View section

The controller is to handle the user request and respond, usually in response to be displayed in the browser, using HTML code, the browser is recognized. HTML has images, text, input controls, and so on. The design that is commonly called the user interface is the UI layer, which is called View in ASP.

Experiment two--in-depth understanding of view

In experiment two, create a simple MVC application that only has a controller and a simple string type of return value. Let's take a look at the view part of MVC.

    • step1– Creating a new action method

Add a new action method in TestController, as follows:

   1: Public  actionresult GetView ()
   2:  
   3:     return View ("MyView"); 
   4:  }

    • Step 2 CREATE View
    • Step 2.1 Right click on the action method created above and select "Add View"

    • Step 2.2 In the Add View dialog box, enter the view name "MyView", deselect the "Use Layout" check box, click Add.

A new view file is added to the Views/test folder in the resource manager.

    • Step3 Adding content to view

Open the Myview.cshtml file, and add the following:

@{layout = null;} <! HTML><html><head><namecontent/><  Title>myview</title></head><body>  

    • Step 4. Run the app by pressing the F5 key

Experiment Two: Q&a

1. Why is the view placed in the test folder?

View is related to the controller that is placed in a specific directory. This particular folder is named "Controllername" and placed inside the view folder

2. Can I reuse view in multiple controllers?

Of course, we need to put these files in a specific shared folder. All controllers in the shared folder are available.

3. Can I refer to multiple view in a single action method?

Yes, the view and controller of ASP. NET MVC are not strictly matched, one action method can refer to multiple view, and a view can be used by an action approach as shown in the following code:

   1: Public  actionresult GetView ()
   2:  {
   3:      if (some_condition_is_matching)
   4:      
   5:         return View ("MyView"); 
   6:      }
   7:      Else
   8:      {
   9:         return View ("YourView"); 
  Ten:      }
  One:  }


4. What is the function of the view function?

Creating a ViewResult object will be rendered as a view to give feedback to the user

    • ViewResult created the Viewpageactivator object
    • ViewResult selected the correct viewengine and will pass the parameters of the Viewpageactivator object to the Viewengine constructor.
    • Viewengine creating an object of the view class
    • Viewengine calls the view's Renderview method.

5. What is the relationship between ActionResult and Viewresult?

ActionResult is abstract class, and Viewresult is ActionResult's multilevel child node, multilevel is because Viewresult is a subclass of Viewresultbase, And Viewresultbase is the child node of ActionResult.

6. What is Contentresult?

Viewresult is an HTML response and Contentresult is a standard text response, returning only the string type. The difference is that Contentresult is a subclass of ActionResult.

in the next section, we will discuss models, validations, jquery, and JSON. So keep your eye on it!

Chinese original link: http://www.cnblogs.com/powertoolsteam/p/MVC_one.html

English original link: Http://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day

Reproduced ASP (i)--deep understanding of ASP. NET MVC

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.