7 days to switch ASP. net mvc-1st days, asp. netmvc

Source: Internet
Author: User

7 days to switch ASP. net mvc-1st days, asp. netmvc
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 pleasant Monday, and then become an ASP. net mvc developer on the weekend. This is cool.


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 &.


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.

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.


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.

ASP. NET Web Forms

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:

1. Response Time: What is the time for the Server to respond to the request?
2. 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.


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.


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

<input name="TextBox1" type="text" value="Make it simple" id="TextBox1"><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.Button1_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 Button1_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.

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:


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.


How ASP. net mvc solves 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.


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.


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.

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?


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


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.


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.

Understanding Controller from simple MVC Hello World
  • Create an ASP. net mvc 5 program

1. Open Visual Studio 2013 or later, and click File> New> project.


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


3. Select the MVC Template File


4. Click Change permission and select "no permission" in the dialog box 」.


5. Click OK.

  • Create a Controller

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


2. Select the MVC 5 controller and click Add.


3. Name the controller "TestController" and click "add.

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


  • 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.


Q & A for 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 an 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.


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?

1. Directly override the class method "ToString.

public override string ToString()  
{
    return this.CustomerName+"|"+this.Address;
}

2. Press F5 to view the output result.


  • 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.


Understanding 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.

Demonstrate 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 」.


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


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


  • Open the "MyView. cshtml" file and you will see the following content.
@{    Layout = null;}<!DOCTYPE html>  

 
  • Test and run

Press F5 to execute the application


Q & A for 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 」.


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.

1. Create a ViewPageActivator object in ViewResult.
2. Select the correct ViewEngine for ViewResult and transmit the ViewPageActivator object as a parameter to the ViewEngine constructor.
3. ViewEngine creates a View class object.
4. 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

This article is compiled by OneAPM engineers. OneAPM is an emerging leader in the application performance management field. It helps enterprise users and developers easily achieve slow real-time crawling of program code and SQL statements. For more technical articles, visit the official OneAPM blog.


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.