7-day experience ASP. net mvc-1st days, asp. netmvc

Source: Internet
Author: User

7-day experience ASP. net mvc-1st days, asp. netmvc

0. Preface
As the title "7 days to play ASP. net mvc" says, this is a series of articles, so we will release 7 articles to you one after another. Imagine that one article a day, you will start reading from a happy Monday, and then become an ASP. net mvc developer on the weekend. This is cool!

7-day transition to ASP. net mvc-1st-day

The first day is the warm-up exercise. This article will focus on two Labs: Controller and Views. In each Lab, there are some Question and Answer. Therefore, the main framework of this article is Lab and Q &.

7-day transition to ASP. net mvc-1st-day

1. Preparations before start
We only need Visual Studio Tools to start the ASP. net mvc journey. You can download the required version from the Visual Studio website.

2. MVC vs Webforms
When many ASP. NET developers first came into contact with MVC, they thought it was different from Webforms and thought it was a brand new technology. Indeed, if ASP. NET Webforms is a framework for creating Web applications, so ASP. net mvc is a better architecture system. It organizes and places our code in a more reasonable way.

It is undeniable that ASP. NET Webforms have been very popular over the past 10 years. Since VB, Microsoft began to preach the RAD and Visual Programming methods. Even Microsoft's development tools are called Visual Studio.

By using Visual Studio, developers can drag and drop the UI components to the design interface, and Visual Studio automatically generates C # Or VB. NET code for these components. These can be called "Code Behind". In the "Code Behind" area, developers can write some logic Code.

7-day transition to ASP. net mvc-1st-day

Therefore, Microsoft's Visual RAD method is actually two things: UI and Code Behind. For example, ASP. NET Webforms include ASPX and ASPX. CS. for WPF, there are XAML and XAML. CS.

3. ASP. NET Web Forms problems
Since ASP. NET Webform is so successful, why should Microsoft consider creating ASP. net mvc? The main reason is the performance of ASP. NET Webform. You can consider the following two performance perspectives:

Response time: What is the time for the Server to respond to the request?
Bandwidth consumption: how much data is transmitted?
Let's try to explain why ASP. NET Webforms has a slow response time. Through a small load test, we found that ASP. net mvc is about twice faster than ASP. NET Webforms.

7-day transition to ASP. net mvc-1st-day

Suppose ASPX has such a simple code about Text Box.

<Asp: TextBox ID = "TextBox1" runat = "server">
Then, write some background logic code for the Text Box and assign values and background colors to it.

Protected void Page_Load (object sender, EventArgs e)
{
TextBox1.Text = "Make it simple ";
TextBox1.BackColor = Color. Aqua;
}
After running the program, the output is displayed on the HTML page.

7-day transition to ASP. net mvc-1st-day

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

<Input name = "TextBox1" type = "text" value = "Make it simple" id = "TextBox1" style = "background-color: Aqua;"/>
Stop reading now, 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 long server response journey just to display such a simple page in a browser?
Isn't it difficult for developers to write HTML pages directly?
7-day transition to ASP. net mvc-1st-day

In fact, every request has a Conversion logic running, which is used to convert the HTML output control. When the output control is some Grids tables, Tree View Tree controls, and other complex HTML pages, this conversion will become more time-consuming and complex, so that the waiting time is longer.

To solve this problem, we began to discard "Code Behind" and write some pure HTML.

Developers who have been engaged in ASP. NET for a long time must be very familiar with Viewstate, which can automatically save the status returned by post and reduce the development time. However, because the decrease in development time brings a huge cost, Viewstate increases the page size. Through Load Testing and comparing ASP. net mvc, we found that Viewstate has increased by nearly twice the page size.

7-day transition to ASP. net mvc-1st-day

The increase in the Viewstate size is because additional bytes are generated. Is a snapshot of Viewstate. Some may refute the idea of giving up Viewstate, but for developers, if there are other options, they will try other options.

7-day transition to ASP. net mvc-1st-day

To solve this problem, we should abandon the Server control.

Custom HTML
Because we use ASP. NET controls and background code to write applications, we have no way to determine what HTML is output or how efficient they are. For example, we can look at a piece of ASPX code. You can try to guess what 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">
Will 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, the Literal control 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>
Therefore, instead of using the Server Control to generate HTML, it is better to write HTML directly to implement some HTML controls.

Therefore, the solution is to directly write some HTML without using the Server control. Writing HTML directly brings some benefits, which enables Web designers to work closely with the development team. Web designers can use DreamWeaver or FrontPage to independently design and obtain HTML code. If we use server controls, these design tools cannot be well identified.

Reusable background code
If you have seen a professional ASP. NET Webform project, you will find that its background code often contains a large amount of code, and the code is really complicated. These codes inherit the "System. Web. UI. Page" class, which is not a common class and cannot be reused or instantiated. In other words, you can never do this in a Webform class:

WebForm1 obj = new WebForm1 ();
Obj. button#click ();
Because the "WebForm" class does not have "Request" and "Respnse" objects, they cannot be instantiated. You can see the "ButtonClick" Event code of "WebForm" in the following code. From this code, you can see why instantiation is difficult to implement.

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

4. Solution
Through the previous analysis, we found two key factors of ASP. NET Webforms: "Code Behind" and "Server Controls", namely, the background Code and Server control. The impacts and solutions are as follows:

7-day fun ASP. net mvc-1st-day

The solution we need is to migrate the background code to an independent simple class library, discard the ASP. NET Server Control, and write some simple HTML pages. In short, the solution is like an image that shows how to "lose weight" Web Form into MVC.

7-day fun ASP. net mvc-1st-day

5. How does ASP. net mvc solve Webforms problems?
As we have discussed earlier, background tasks and server controls are the root cause of the problem. So if you look at the current Webform architecture system, you will find that developers use almost three-layer architecture systems.

The three-layer architecture includes the UI, which actually contains the ASPX and background code.

7-day transition to ASP. net mvc-1st-day

ASP. net mvc consists of three parts: Model, View, and Controller. The Controller is responsible for the background logic code. View is a pure HTML page. Model is the intermediate data layer.

There are two major changes here. One is that the View changes to a simple HTML page, and the other is that the background code is converted to a simple. NET class, which we call Controller.

The request stream of ASP. net mvc is as follows:

Step 1: first trigger the Controller.

Step 2: create a Model object based on the behavior Controller. In turn, the Model calls the data interface layer to populate the data with the Model object.

Step 3: The filled Model object transmits the data to the View layer and then displays it.

7-day fun ASP. net mvc-1st-day

Now we have understood the various components of ASP. net mvc. Next, I will start to learn more about each component and make some small Lab. We will start with Controller because it is the core of the MVC Architecture.

6. How to understand Controller in ASP. NET MVC
To understand the Controller, we must first understand the concept of "user interaction logic.

What is interaction logic?

Scenario 1
Have you ever thought about what will happen when the end user clicks a URL in the browser and press enter?

7-day fun ASP. net mvc-1st-day

The browser sends a request to the server, and the server then responds.

7-day fun ASP. net mvc-1st-day

In this way, the client tries to interact with the server. The server can return a response because the server already has some logic to process these requests. This logic actually carries the user's requests and the interaction between the user and the server. This 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-day transition to ASP. net mvc-1st-day

What happens when you click "SaveCustomer?

If your answer is "some event processors handle this button and click", it will be wrong.

In reality, Web programming has no concept of events. One case is that Microsoft has written some code for ASP. NET Webforms and gives us the feeling of event-driven programming. In fact, this is just an illusion or fantasy.

When a button is clicked, a simple HTTP request is sent to the server. The difference is that the values of "Customer Name", "Address", and "Age" are sent along with the request. Basically, if a request occurs, the server will send a response based on the prepared logic. In short, there must be some user interaction logic on the server.

In ASP. net mvc, the last letter "C" represents Controller, which is used to process user interaction logic.

7. Lab1-Understanding Controller from simple MVC Hello World
Create an ASP. net mvc 5 program
Open Visual Studio 2013 or later, and click File> New> project.

7-day fun ASP. net mvc-1st-day

Select a Web application, enter the application name, select the application path, and click OK.

7-day fun ASP. net mvc-1st-day

Select the MVC Template File

7-day fun ASP. net mvc-1st-day

Click Change permission. In the dialog box, select "no permission 」.

7-day fun ASP. net mvc-1st-day

Click OK.

Create a Controller
In resource manager, right-click the Controller folder and choose add> Controller.

7-day transition to ASP. net mvc-1st-day

Select the MVC 5 controller and click Add.

7-day fun ASP. net mvc-1st-day

Name the controller "TestController" and click "add.

It is very important not to delete the word "Controller", which is the keyword of the Controller.

7-day fun ASP. net mvc-1st-day

Create Behavior Method
Open the newly created "TestController" class and you will find that there is a method named "Index" in it, delete this method, and create a new public method called "GetString 」.

Public class TestController: Controller
{
Public string GetString ()
{
Return "Hello World is old now. It's time for wassup bro ;)";
}
}
Execute and Test
Press F5. Enter "ControllerName/ActionName" in the address bar. However, do not add the Controller name "Controller". Simply enter "Test.

7-day fun ASP. net mvc-1st-day

8. Q & A around Lab 1
What is the relationship between TestController and Test?
"TestController" is the name of a class, but "Test" is indeed the name of a controller. Note that when you enter the Controller name in the URL, do not include the word "Controller 」.

What is the Action "Action" method?
The Action method is a simple public method in the Controller. It is responsible for receiving user requests and returning some responses. Through the above example, we can see that the behavior method "GetString" returns 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 requests, we have to create an HTTP processor, rewrite the content type, and then respond. This is not a simple task. But it is easy in ASP. net mvc. If you return a String, you do not need to return a complete HTML page.

What happens if an object is returned in an Action method?
View 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-day fun ASP. net mvc-1st-day

When the returned type is an object such as "Customer", it returns the implementation method "ToString ()" of the object ()」. The method ToString () returns the full name of the class by default, that is, the form of NameSpace. ClassName.

What should I do if I want to get the attribute values of the preceding example?
You can directly override the "ToString" method of the class.

Public override string ToString ()
{
Return this. CustomerName + "|" + this. Address;
}
Press F5 to view the output result.

7-day fun ASP. net mvc-1st-day

Must the public modifier be added before the Action method?
The answer is yes. The Public modifier is automatically added to the Action method.

How do I understand non-Public methods?
These non-Public methods are only non-Public methods within the class. Simply put, they cannot be called by the Web.

If we want to implement a Public non-Action method, what should we do?
Simply add the NonAction attribute.

[NonAction]
Public string SimpleMethod ()
{
Return "Hi, I am not action method ";
}
When we try to call the following Action method, we will get the following response.

7-day fun ASP. net mvc-1st-day

9. Understand Views in ASP. NET MVC
As we just understood, the Controller is used to process user requests and return responses. In most cases, the response is an HTML page, which can be well understood by the browser. HTML has some images, text, and input controls. In general, the layer that defines user interface design in the technical field is called the UI Layer and ASP. net mvc is called the View layer.

10. Lab2-demo Views
In Lab1, we created a simple MVC application with only some controllers and some simple return values. Now let's add the View section for MVC.

Create an Action Method
Add an Action method to TestController.

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

7-day fun ASP. net mvc-1st-day

In the "Add View" dialog box, Add a View named "MyView". deselect the "Use a layout" check box and click "Add 」.

7-day fun ASP. net mvc-1st-day

In the solution browser, a new view is added to the "Views/Test" folder.

7-day fun ASP. net mvc-1st-day

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

ASP. NET MVC

11. Q & A around Lab 2
Why is the view stored in the Test folder?
In ASP. net mvc, Views are always associated with a specific Controller and put in a special folder. This special folder will be named after the Controller and put in the Views folder (which is located in the root folder ). The view to be accessed by each Controller is only available in the correct folder.

For example, all views associated with TestController will be placed in 「~ /Views/Test, and TestController can only access the view under the Test folder.

Can multiple controllers reuse some views?
The answer is yes. We put these view files in a specified folder, that is, "Shared 」.

7-day transition to ASP. net mvc-1st-day

View files in the Shared folder can be Shared by all controllers.

Can an Action method reference 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 function?
Create a ViewResult object for the view to respond.

Create a ViewPageActivator object in ViewResult.
Select the correct ViewEngine for ViewResult, and transmit the ViewPageActivator object as a parameter to the ViewEngine constructor.
ViewEngine creates a View class object.
ViewResult calls the RenderView method of the View class.
Association between ActionResult and ViewResult?
ActionResult is an abstract class, And ViewResult is a multi-layer subclass of ActionResult. In multiple layers, ViewResult is a subclass of ViewResultBase, and ViewResultBase is a subclass of ActionResult.

If we want to return ViewResult, why is the returned type defined as 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. In some other scenarios, we call the "Content" function to return the Content result.

What is ContentResult?
ViewResult presents a complete HTML response while ContentResult is a plain text response. It is like returning a pure String type. The difference is that ContentResult is an ActionResult type that wraps String results. ContentResult is also a subclass of ActionResult.

Can I call the View function without any parameters?
The answer is yes. The View function uses the current "ActionName" to find the View.

What will we learn in 2nd days?
In 2nd, we will discuss Models, Validation, Jquery, and Json. So, let's swing and learn together!

Original article address: Learn MVC Project in 7 days

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.