7 days to go to mvc-ASP. 1th Day

Source: Internet
Author: User

0. Preface
As the title "7 days to play to the net mvc" said, this is a series of articles, so will be introduced to everyone 7. " Imagine that one day, you'll start reading from a happy Monday, and then become an ASP. NET MVC developer on the weekends, which is cool!

7 days Fun Turn ASP mvc-1th Day

The first day is a warm-up exercise, this article we will be around Controller and views practice two Labs. Each Lab is accompanied by some Question and Answer. So the main frame of the article is Lab and Q&a.

7 days Fun Turn ASP mvc-1th Day

1. Preparation Before you begin
We only need Visual Studio tools to start the ASP. NET MVC Tour. You can download the required version from the Visual Studio website.

2. MVC vs Webforms
Many ASP. NET developers think it is different from Webforms when they first contact with MVC, and think it is a new technology. Indeed, if ASP. NET Webforms is a framework for creating WEB application, then ASP. NET MVC is a better architecture that organizes and places our code in a more rational way.

Admittedly, the net Webforms has been very popular for the past more than 10 years, and since the beginning of VB, Microsoft has been staring at to preach RAD and Visual programming methods. Even Microsoft's development tools, called Visual Studio, are visible.

By using Visual Studio, developers can drag and drop UI artifacts into the design interface, and Visual studio automatically generates C # or vb.net code for those artifacts. These can be referred to as "code behind", where developers can write some logic code within the "code behind" area.

7 days Fun Turn ASP mvc-1th Day

So Microsoft's Visual RAD approach is actually two things, UI and Code Behind. For example, ASP. NET Webforms, with ASPX and ASPX.CS; for WPF, there are XAML and XAML.CS.

3. Problems with ASP. NET Web Forms
Since ASP. Webform is so successful, why should Microsoft consider creating ASP. The main reason is the performance of the ASP. NET Webform. It can be considered from two performance points of view:

Response time: What is the Server-side response time of the request?
Bandwidth consumption: How much data is being transmitted?
Let's try to explain why the ASP. NET Webforms response time is slow. With a small load test, we found that ASP. NET MVC is about twice times faster than ASP. Webforms.

7 days Fun Turn ASP mvc-1th Day

If ASPX has such a simple code for Text Box.

<asp:textbox id= "TextBox1" runat= "Server" >
Then write some background logic code for the Text Box and perform the assignment and background color operation.

protected void Page_Load (object sender, EventArgs e)
{
TextBox1.Text = "Make it simple";
Textbox1.backcolor = Color.aqua;
}
After you run the program, you will see the output on the HTML page.

7 days Fun Turn ASP mvc-1th Day

If you look at the source code of the HTML, it is like this:

<input name= "TextBox1" type= "text" value= "Make it Simple" id= "TextBox1" style= "Background-color:aqua;"/>
Now stop reading and close your eyes and think for a moment:

Is this really an efficient way to create HTML? Do we really need to start such a lengthy server response journey just to show such a simple page on the browser?
Isn't it hard for developers to write HTML pages directly?
7 days Fun Turn ASP mvc-1th Day

In fact, every request will have one Conversion logic running, which is used to transform the HTML output of the control. When the controls we output are some complex HTML pages such as Grids tables, tree View trees, and so on, this conversion becomes more time-consuming and complex, making the wait longer.

To solve this problem, start to abandon "code behind", write some pure HTML.

Developers who have been working with ASP for a long time must be very familiar with Viewstate, which automatically saves the status of post return and reduces development time. But it is because of this reduction in development time that there is a huge cost, Viewstate increases the size of the page. With load testing, compared to ASP. NET MVC, we found that Viewstate has increased the page size by nearly two times.

7 days Fun Turn ASP mvc-1th Day

The increase in size is due to the extra bytes produced by Viewstate. is a snapshot of Viewstate. Some may refute the idea of abandoning Viewstate, but for developers, if there are other options, they will try other options.

7 days Fun Turn ASP mvc-1th Day

To solve this problem, start discarding the Server control.

Custom HTML
Because we write the application through the ASP. NET control and background code, we have no way of deciding what HTML is to be output or how efficient it is. For example, we can look at an ASPX code, and you can try to guess what kind of HTML will be generated.

<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" text= "I am a Panel" >
Does the label control generate a DIV or SPAN label? If you run the code you will find that the Label control is converted to a Span,literal control that is converted to a simple Text, and the Panel control is converted to a DIV.

<span id= "Label1" >i am label</span>
I am Literal
<div id= "Panel1" >i am panel</div>
So instead of using the Server control to generate HTML, it's better to write some HTML directly to implement some HTML controls.

So the solution is to not use the Server control and write some HTML directly. Writing HTML directly also brings some benefits, allowing WEB designers to work closely with the development team. WEB designers can use DreamWeaver or FrontPage to design and get HTML code independently. If we use server controls, these design tools will not be well recognized.

Background Code reusability
If you see a professional ASP. NET Webform project, you will find that its background code often contains a lot of code, and the code is really complicated. The code inherits the "system.web.ui.page" class, and this class is not a regular class, and it cannot be reused or instantiated. In other words, you can never do such a thing in a Webform class:

WebForm1 obj = new WebForm1 ();
Obj. Button1_Click ();
Because the "webform" class does not have "request" and "respnse" objects, they cannot be instantiated. You can see the "webform" "buttonclick" event code from the code below, and you can see why instantiation is difficult to implement in this code.

protected void Button1_Click (object sender, EventArgs e)
{
The logic which you want to reuse and invoke
}
Unit Test
Based on the previously mentioned background code cannot be instantiated directly, so it is conceivable that unit testing or automated testing is very difficult. Developers can only run apps automatically for manual testing.

4. Solution
With previous analysis, we found two key factors for ASP. Webforms: "code behind" and "server controls", which are background code and server controls. They affect the cost and solution as shown in:

7 days to go to mvc-ASP. 1th Day

The solution we need is to migrate the backend code to a separate, simple class library, and discard the ASP. NET Server controls and write some simple HTML pages. In short, the solution is like an image description that will Web form"weight loss" as MVC. "

7 days to go to mvc-ASP. 1th Day

5. How ASP. NET MVC solves Webforms problems
As we discussed earlier, background tasks and server controls are the root cause of the problem. So if you look at the current Webform architecture, you'll find that developers are using almost a 3-tier architecture.

The 3-tier architecture includes the UI, which actually contains ASPX and background code.

7 days Fun Turn ASP mvc-1th Day

ASP. NET MVC contains three parts, the Model,view and the Controller. The Controller is responsible for the background logic code. View is a pure HTML page. Model is the intermediate data layer.

Here are two major changes, one is that View becomes a simple HTML page, and the other is that the backend code is converted to a simple. NET class, which we call a Controller.

The request flow for ASP. NET MVC is as follows:

First step: First trigger Controller.

Step Two: Create the Model object from the behavior Controller. The model in turn populates the model object with data by invoking the data interface layer.

The third step: the filled Model object transmits the data to the View layer and then shows it.

7 days to go to mvc-ASP. 1th Day

Now we have understood the various components of ASP. Next, start learning each component in depth and do some small labs. We'll start with the Controller because it's the core of the MVC architecture.

6. How to understand the Controller in ASP.
In order to understand the controller, we first need to understand the concept of "user interaction logic".

What is interactive logic?

Scenario 1
Have you ever thought about what happens when an end user taps a URL on the browser and presses ENTER?

7 days to go to mvc-ASP. 1th Day

The browser sends a request to the server and the server responds again.

7 days to go to mvc-ASP. 1th Day

In this way, the client attempts to interact with the server. The server is able to return a response because the server has some logic to handle these requests. This logic actually carries the user's request and the user's interaction with the server, which is the user interaction logic.

Scenario 2
There is a possibility that the response returned by the server is an HTML response. This HTML contains some input boxes or submit button components.

7 days Fun Turn ASP mvc-1th Day

What happens when I click the "savecustomer" button?

If your answer is "some event handlers to handle this button click," Then it's wrong.

The reality is that WEB programming is not a concept of events. One scenario is that Microsoft has written some code for us for ASP. Webforms, and gives a sense of event-driven programming. In fact, this is just an illusion or illusion.

When the button is clicked, a simple HTTP request is sent to the server. This time the difference is that the values of "customer name","address" and "age" will be sent along with the request. Fundamentally, if a request is made, the server sends back a response based on the logic already written, in short, there must be some user interaction logic on the server.

In ASP., the last letter "c" represents the Controller, which is used to handle the user interaction logic.

7. Lab1-Understand Controller from simple MVC Hello world
Creating an ASP. NET MVC 5 program
Open Visual Studio 2013 or later, click File > New > Project.

7 days to go to mvc-ASP. 1th Day

Select the Web app, fill in the app name, select the application path, and click OK.

7 days to go to mvc-ASP. 1th Day

Select the MVC template file

7 days to go to mvc-ASP. 1th Day

Click Change Permissions and select "No Permissions" in the dialog box.

7 days to go to mvc-ASP. 1th Day

Click OK.

Create a Controller
In Explorer, right-click the "controller" folder and click Add > Controller.

7 days Fun Turn ASP mvc-1th Day

Select the MVC 5 controller and click Add.

7 days to go to mvc-ASP. 1th Day

Name the controller "testcontroller", then click Add.

It is important to not delete the word "controller", which is the controller's keyword.

7 days to go to mvc-ASP. 1th Day

Create a Behavior method
Open the "testcontroller" class you just created, and you'll find a method called "index", which removes the method, and then creates a new public method called "getstring".

public class Testcontroller:controller
{
public string GetString ()
{
Return "Hello world are old now." It ' s time for wassup bro;) ";
}
}
Execute and test
Press the F5. In the Address bar, enter in "controllername/actionname" format. However, it should be noted that the name of the controller should not be "controller" Plus, write "test" directly.

7 days to go to mvc-ASP. 1th Day

8. Q&a around Lab 1
The relationship between TestController and Test?
"testcontroller" is the name of a class, but "test" is indeed the name of a controller. It is important to note that when you enter the name of the controller in the URL, do not bring the word "controller".

What is the action"behavior" method?
The Action method is a simple public method in the controller that is responsible for receiving the user's request and returning some responses. Using the above example, you can see that the behavior method "getstring" is to return a string response.

Note: in ASP. NET Webforms, HTML is returned by default. One scenario is that if we want to return some other non-HTML type of request, we have to create an HTTP processor, rewrite the content type, and then respond. This is not a simple task. But it's easy in ASP. You return a "string" as you return to "string", and you do not need to return a full HTML page.

What happens if, in an Action method, the return is an object?
Review the following code.

Namespace Webapplication1.controllers
{
public class Customer
{
public string CustomerName {get; set;}
public string Address {get; set;}
}
public class Testcontroller:controller
{
Public Customer GetCustomer ()
{
Customer C = new Customer ();
C.customername = "Customer 1";
c.address = "Address1";
return C;
}
}
}
The output Action method is as follows.

7 days to go to mvc-ASP. 1th Day

When the returned type is an object such as "customer", it returns the object's implementation method "tostring ()". Method "tostring ()" Returns the full name of the class by default, which is the form of "namespace.classname".

What if you want to get the property values for the above example?
The method of overriding the class directly "tostring".

public override string ToString ()
{
return this. Customername+ "|" +this. Address;
}
Press F5 to view the output.

7 days to go to mvc-ASP. 1th Day

Must I add the public modifier before the Action method?
The answer is yes, the Action method automatically adds the public modifier.

How is the non-public method understood?
These non-public methods are only private methods within the class, and the simple understanding is that they cannot be called by the Web.

What if we want to implement a public non-Action method?
Simply add the Nonaction attribute to it.

[Nonaction]
public string Simplemethod ()
{
Return "Hi, I am not action method";
}
When we try to invoke the following Action method, we get the following response.

7 days to go to mvc-ASP. 1th Day

9. Understanding views in ASP.
As we have just understood, the Controller is used to process a user's request and return a response. In most cases, the response is an HTML page, and the browser can understand the format well. HTML has some pictures, text, input controls and so on. In general, the layer defining the user interface design in the technical realm is called the UI layer, which is called View in ASP.

LAB2-Demo views
In LAB1 we created a simple MVC application with only a few controllers and some simple return values. Now let's add the View section to MVC.

Create an Action method
Add an Action method to the TestController.

Public ActionResult GetView ()
{
Return View ("MyView");
}
Create a View
Right-click the Action method and select "add view".

7 days to go to mvc-ASP. 1th Day

In the "add view" dialog box, add a view, name "myview", cancel "use a layout" check box, and click "add".

7 days to go to mvc-ASP. 1th Day

In the Solution Explorer, you will find that the "views/test" folder adds a new view.

7 days to go to mvc-ASP. 1th Day

Open the "myview.cshtml" file and you will see the following.
@{
Layout = null;
}
<! DOCTYPE html>
<meta name= "viewport" content= "Width=device-width"/>
<title>MyView</title>
<body>
Welcome to MVC 5 step by Step learning
<body>
Test and run
Press F5 to execute the application

7-Day fun-to-go ASP.

11. Q&a Around Lab 2
Why is the view placed under the Test folder?
in ASP. NET MVC, views are always associated with a particular Controller and placed in a special folder. This special folder will be named after the Controller and placed in the Views folder (it is located in the root folder). For each view the Controller wants to access, it is only available in the correct folder.

For example: All views of the associated TestController will be placed under "~/views/test", and TestController can only access the view under the Test folder.

Can I reuse some views for multiple controllers?
The answer is yes. We put these view files under a specified folder, that is, "shared".

7 days Fun Turn ASP mvc-1th Day

The view file under the "shared" folder can be shared by all controllers.

Can an Action method refer to multiple views?
The answer is yes. The following code:

Public ActionResult GetView ()
{
if (some_condition_is_matching)
{
Return View ("MyView");
}
Else
{
Return View ("YourView");
}
}
What is the purpose of the view feature?
Creates a ViewResult object for the view to respond to.

ViewResult creating Viewpageactivator Objects internally
ViewResult selects the correct viewengine and transmits the Viewpageactivator object as a parameter to the Viewengine constructor.
Viewengine creates an object of the View class.
ViewResult invokes the Renderview method of the View class.
The association between ActionResult and ViewResult?
ActionResult is an abstract class, and ViewResult is a multilayer subclass of ActionResult. Multilayer is because ViewResult is a subclass of Viewresultbase, and Viewresultbase is a subclass of ActionResult.

If we want to return ViewResult, why is the return type defined to be ActionResult?
This is to achieve polymorphism, see the following example:

Public ActionResult GetView ()
{
if (some_condition_is_matching)
{
Return View ("MyView");
}
Else
{
Return Content ("Hi Welcome");
}
}
In the above example, in some scenarios, we call the "view" function to return the ViewResult type, while in some other scenario we call the "content" function to put back the content result.

What is Contentresult?
ViewResult renders a full HTML response while Contentresult renders a plain text response. It's like returning a pure String type meaning. The difference is that Contentresult is a actionresult type that wraps a string result. Contentresult is also a subclass of ActionResult.

Can I call the View function without a parameter?
The answer is yes. The view function uses the current "actionname" to find the views.

What are we going to learn on the 2nd day?
In the 2nd day, we will discuss Models,validation,jquery and Json. So, let's swing together and learn together!

Original address: Learn MVC Project in 7 days

7 days to go to mvc-ASP. 1th Day

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.