Pro ASP. NET Core MVC version 6th Chapter 2 (first half chapter), mvc half chapter

Source: Internet
Author: User
Tags microsoft edge

Pro ASP. NET Core MVC version 6th Chapter 2 (first half chapter), mvc half chapter
Directory Chapter 2 first MVC application

The best way to learn a software development framework is to jump inside and use it. In this chapter, you will use ASP. NET Core MVC to create a simple data login application. I will show it step by step so that you can see how to build an MVC application. To make things simple, I skipped some technical details, but don't worry. If you are a beginner in MVC, you will find many things that are sufficient to mention your interest. Because I have not explained some of the things I use, I provide some reference so that you can see all the details.

Install Visual Studio

Visual studio 2015 must be installed according to the practice in this book. It provides everything you need to Develop ASP. NET Core MVC. I use Visual Studio 2015 Community for free. You can download it from www.visualstudio.com. Make sure that the Microsoft web development Tools option is selected during installation.

 

Tip: Visual Studio only supports Windows platforms. on other platforms, you can use Visual Studio Code for development. However, it does not provide all the tools required for the sample programs in this book, see Chapter 1.

 

If you have already installed Visual Studio, you must ensure that Visual Studio Update 3 is available because it supports ASP. NET Core development. If it is a new installation, Update3 will be automatically installed. If you only need Update, you can go to http://go.microsoft.com/fwlink? LinkId = 691129 download it here.

 

Then you have to download and install. NET Core, here: https://go.microsoft.com/fwlink? LinkId = 817245

. That is, it is a newly installed Visual Studio, and you also need to download. NET Core.

 

In the last step, you must download and install git. Here you can download: https://git-scm.com/download.

Visual Studio contains its own version of git, but it is not easy to use and sometimes produces unpredictable things. For example, it is used with other tools such as Bower. I will talk about Bower in Chapter 1. When installing git, tell the installer to add the tool to the PATH environment variable to ensure that Visual Studio can find the new version of git.

 

Figure 2-1 adds git to path.

 

Start Visual Studio, select Tools> Options, and navigate to project and solution> Expand Web Tools, 2-2. Remove the check box $ (VSINSTALLDIR) \ Web \ External \ Git to invalidate the version that comes with Visual Studio, but make sure that the $ (Path) item is valid to use the version just installed.

 

Figure 2-2 configure git in Visual Studio.

 

 

 

 

Create a new ASP. NET Core MVC Project)

I will create a new ASP. NET Core MVC project in Visual Studio. In Visual Studio, select New-> Project from the menu to open the New Project dialog box. If you navigate to Template-> Visual C #-> Web item in the left sidebar, you will see ASP. NET Web Application (. net Core) Project template, select this project type, as shown in Figure 2-3.

 

 

Figure 2-3 Visual Studio Core Web Application Engineering Template

 

Tip: it may be a bit confusing when selecting a project template, because they are similar. ASP. NET

The Web Application (. NET Framework) template is used to create a project using ASP. NET and ASP. net mvc frameworks. It is an earlier version of ASP. NET Core. The other two templates are used to create ASP. NET Core applications, but use different runtime libraries. You can select between. Net Framework and. NET Core. I will explain the differences between them in Chapter 6th. However, I use the. NET Core option in the whole book, so it is your only choice to ensure that you run the example application to get the correct results.

 

Set the name of the new Project to PartyInvites and make sure that the Add Application Insights to Project option is not selected. 2-3. Click OK to continue, and then you will see another dialog box, 2-4, which will let you set the initial content of the project.

 

There are three ASP. NET Core template options, each of which uses different initial content to create a project. In this chapter, select the Web Application option. You can use the predefined content to create an MVC Application for development.

 

Note: This is the only chapter that uses the Web Application Engineering Template. I don't like predefined project templates because they encourage developers to treat some important features like a black box, such as identity verification. In this book, my goal is to help you understand and manage every aspect of MVC applications. Therefore, I will use empty templates to start a project later in this book. In this chapter, I want you to get started quickly. This template is suitable.

 

Click the Change Authentication button and select the No Authentication option 2-5. This project does not require authentication, but I will explain in chapter 28-30 how to ensure the security of ASP. NET applications.

 

Figure 2-5 select Authentication Settings

 

Click OK to close the Change Authentication dialog box. Make sure that the Host in the Cloud is not selected, and click OK to create the PartyInvites project. Once Visual Studio has created a project, you will see some files and folders displayed in the solution window, 2-6. This is the default structure of the new MVC project created using the Web application template. You will soon be able to understand the role of every file and folder here.

 

 

Figure 2-6 initial file and folder structure in ASP. NET Core MVC Project

 

You can select Start Debugging from the Debug menu (if it prompts you to enable Debugging, click OK). After you do this, Visual Studio compiles and generates the application, run the application server called IIS and open the Web browser to request the application content. The following result is displayed: 2-7.

 

 

 

Figure 2-7 run the example project

 

When Visual Studio uses a Web application template to create a project, it adds the basic code and content to it. When you run the project, you can also see the content. Next, in this chapter, I will replace the content in the project to create a simple MVC application.

 

After completing these steps, if the browser displays an error message, close the browser window to stop debugging. Alternatively, return to Visual Studio and select Stop Debugging from the Debug menu.

As you can see just now, Visual Studio opens a browser to display the project. In the Web Browser menu, you can click the right arrow of IIS Express and select any Browser you have installed from the options list. 2-8.

 

 

Figure 2-8 select a browser

 

From here on, I will use Google Chrome or Google Chrome Canary in this book to take screenshots. However, you can use any modern browser to display examples in this book, including Microsoft Edge and the latest version of Internet Explorer.

 

Add Controller)

 

In MVC mode, incoming requests are processed by the Controller. NET Core MVC, controller is just a class, inherited from the built-in MVC controller base class Microsoft. aspNetCore. mvc. controller.

Every public method in the controller is called an action method. It means that you can use some URLs to perform an action on the Web. According to the traditional MVC conventions, controller classes are generally placed in the controllers folder, which is created by Visual Studio when creating a project.

 

Tip: You don't have to follow the MVC conventions, but I suggest you do this because it is more reasonable.

 

Visual Studio adds the default Controller class to the project. If you expand the Controllers folder in the solution browser window, you will see it. The default Controller is HomeController. cs. The Controller class name ends with Controller, which means that when you see the HomeController. cs file, you will know that it is a Controller called Home, And HomeController is the default Controller of the MVC application. Click the HomeController. cs file and you can edit it. You will see the code shown in List 2-1.

 

List 2-1. Initial content of HomeController

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Threading. Tasks;

Using Microsoft. AspNetCore. Mvc;

Namespace PartyInvites. Controllers {

Public class HomeController: Controller {

Public IActionResult Index (){

Return View ();

}

Public IActionResult About (){

ViewData ["Message"] = "Your application description page .";

Return View ();

}

Public IActionResult Contact (){

ViewData ["Message"] = "Your contact page .";

Return View ();

}

Public IActionResult Error (){

Return View ();

}

}

}

Replace the original code in the HomeController. cs file with the following List 2-2 content. Here, I only keep one method, changed the result type and its implementation, and removed the unnecessary using statements.

 

Listing 2-2. Change HomeController. cs

Using Microsoft. AspNetCore. Mvc;

Namespace PartyInvites. Controllers {

Public class HomeController: Controller {

Public string Index (){

Return "Hello World ";

}

}

}

 

These changes have no dynamic effect, but they are a good demonstration. I have changed the Index method and asked him to return "Hello World ". Click Debug> Start Debugging to run the project again.

 

Prompt: If you keep your application running in the previous section, select Debugging-> Restart. Of course, if you want to, you can choose to stop debugging and then start debugging.

 

The browser will initiate an HTTP request to the server. The default MVC configuration specifies that the request will be processed by the Index method (called Action method or Action). The result of this method will be sent back to the browser, as shown in 2-9.

 

 

Figure 2-9 output of the Action Method

 

Note: In the preceding figure, Visual Studio has directed the browser to port 57628. You can see that the URL port number on your browser is almost certainly different from the figure above. Because VS randomly allocates ports when creating a project. If you see the notification area on the Windows Task Bar, you will find an IIS Express icon, which is a simplified version of the IIS application server, along with, it is used to deliver ASP during development.. NET content and provide services. In Chapter 12th, I will show you how to release an MVC project to the production environment.

 

Understanding Routing

In addition to the Model, View, and Controller, the MVC application also uses the ASP. NET routing system, which contracts to determine how the URL is mapped to the Controller and Action. A route is a rule used to determine and process requests. When VS creates an MVC project, it adds some default routes for you. You can request the following URLs, which all point to the Index action in HomeController.

L/

L/Home

L/Home/Index

 

Therefore, when a browser requests http: // yoursite/or http: // yoursite/Home, it returns results from the Index method of HomeController. You can try changing the URL in the browser by yourself, assuming it is now http: // localhost: 57628. If you add/Home or/Home/Index after the URL and press the Enter key, you will see the same Hello World results.

 

This is a good example of a convention that follows ASP. NET Core MVC implementation. This Convention is: I will have a controller called HomeController, which is the entry point of the MVC application. In the default VS configuration, when it is used to create a new MVC application, it assumes that we follow this convention. Because I follow this convention, I will automatically go to the support in the previous list. If I do not follow this convention, I will have to modify the configuration to point to another Controller. For this simple example, the default configuration is what I need.

 

Rendering Web pages

The output in the previous example is not HTML, but a simple "Hello World" string. To generate HTML for a browser, I need a View that will tell MVC how to generate a response for a request.

Create and render a View

The first thing I need to do is to modify the Index action method, such as program 2-3. The changes I made are displayed in a bold font, and an agreement is also used to make the example very simple.

 

Listing 2-3. Modify Action

Using Microsoft. AspNetCore. Mvc;

Namespace PartyInvites. Controllers {

Public class HomeController: Controller {

Public ViewResult Index (){

Return View ("MyView ");

}

}

}

When I return a ViewResult object from an Action method, I instruct MVC to render a view. I create a ViewResult object by calling the View method, and set the View name MyView when calling the object. If you run this application, you will find that MVC will try to find this View, and an error message such as 2-10 will appear.

 

 

 

Figure 2-10 MVC tries to find a view

 

This error message is very helpful. Not only does MVC not find the View I specified in the action method, but it also tells where to find it. All Views are saved in the Views folder and organized into subfolders. For example, the View associated with the Home controller is saved in a folder called Views/Home. If a View does not have a fixed Controller, it is saved in the Views/shared folder. VS creates the Home and Shared folders when the Web application template is used, and puts some placeholder views to enable the project to start.

 

To create a View, right-click Views> Home in the solution browser window, and select Add> New Item from the pop-up menu. VS shows you some item templates, selects ASP. NET categories in the left column, and selects MVC View Page items in the middle column. 2-11.

 

Figure 2-11 create a View

 

Tip: you will see some files in the Views folder. They are added by VS to provide the initial content as shown in Figure 2-7. You can ignore those files.

 

Set the name field to MyView. cshtml and click Add to create a View. VS will create the Views/Home/MyView. cshtml file and open it for editing. Initially, the View file contains only some comments and placeholders. replace them with Code 2-4.

 

Tip: it is easy to create a view file in the wrong folder. If you haven't finally created MyView. cshtml in Views/Home, delete them and create them again.

 

Listing 2-4. Replace MyView. cshtml File Content

 

@{

Layout = null;

}

<! DOCTYPE html>

<Html>

<Head>

<Meta name = "viewport" content = "width = device-width"/>

<Title> Index </title>

</Head>

<Body>

<Div>

Hello World (from the view)

</Div>

</Body>

</Html>

The new contents of the view file are mostly HTML. The exception is the part that looks like this:

...

@{

Layout = null;

}

...

 

Most of the content in the New View File is HTML, except for this part:

@{

Layout = null;

}

This is an expression interpreted by the Razor View engine. It processes the View content and generates HTML that is sent back to the browser. This is a simple Razor expression. He will tell Razor that I choose not to use layout. Layout is an HTML template. I will explain it in chapter 5. I will ignore Razor and will be back later. To see the effect, click Start Debugging to run the application. You will see the results in Figure 2-12.

 

Figure 2-12 test View

When I edit the Index action Method for the first time, it returns a string, that is, MVC will pass the string value to the browser, without doing anything else. Now, the Index method returns a ViewResult. MVC renders a view and returns its HTML. I told MVC which view to use, so it automatically finds it using naming conventions. This Convention means that the view has the same name as the Action and is saved in the folder named by the Controller.

 

In addition to strings and ViewResult, I can also let the Action method return other types. For example, if I return a RedirectResult, the browser redirects it to another URL. If I return an HttpUnauthorizedResult, I will force the user to log on. These objects are called set control of Action result. The Action Result system allows you to encapsulate and reuse common actions to return results. In Chapter 17, I will introduce more relevant content.

 

Add dynamic output

 

The focus of the entire web application platform is to build and Display Dynamic Output content. In MVC, the Controller is responsible for building some data and passing it to the view. The view is responsible for rendering it into HTML.

One way to transmit data from a controller to a view is to use the ViewBag object, which is a member of the controller base class. ViewBag is a dynamic object. You can assign any attribute to it for rendering. Code 2-5 demonstrates how to pass simple objects in HomeController.

Listing 2-5. Set View data

Using System;

Using Microsoft. AspNetCore. Mvc;

Namespace PartyInvites. Controllers {

Public class HomeController: Controller {

Public ViewResult Index (){

Int hour = DateTime. Now. Hour;

ViewBag. Greeting = hour <12? "Good Morning": "Good Afternoon ";

Return View ("MyView ");

}

}

}

 

I assign a value to the ViewBag. Greeting attribute to provide data to the view. The Greeting attribute does not exist before the value is assigned, which allows me to transmit data from the Controller to the view in any smooth way without defining the class before the value is assigned. I reference the ViewBag. Greeting attribute in the view to obtain its value. Like Code 2-6, this is the modified MyView. cshtml.

 

Listing 2-6. Get the passed value in the view

@{

Layout = null;

}

<! DOCTYPE html>

<Html>

<Head>

<Meta name = "viewport" content = "width = device-width"/>

<Title> Index </title>

</Head>

<Body>

<Div>

@ ViewBag. Greeting World (from the view)

</Div>

</Body>

</Html>

 

The added part of the code above is the Razor expression, which is used to evaluate the value when the view is generated by MVC. When I call the View method in the controller, MVC finds the MyView. cshtml file and requests the Razor View engine to parse the file content. Razor looks for expressions in the above Code. In this example, the processing expression means to insert the ViewBag. Greeting attribute to the view.

 

There is nothing special about the name of the Greeting attribute. You can use any other name and it is equally useful. As long as your name in the controller is the same as that in the view. You can use multiple attributes to transmit multiple data. Run the command to check the effect, 2-13.

 

Figure 2-13 Dynamic Responses of an 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.