Pro ASP. NET Core MVC version 6th chapter II (first half chapter)

Source: Internet
Author: User
Tags microsoft edge

Catalogue Chapter Two the first MVC application

the best way to learn a software development framework is to jump into his interior and use it. In this chapter, you will create a simple data login application with ASP. NET Core mvc. I'll show it step-by-step so you can see how to build an MVC application. To make things simple, I skipped some technical details, but don't worry, if you're a novice in MVC, you'll find a lot of stuff that's enough to bring your interest. Because some of the things I use have not been explained, I have provided some references so that you can see everything in detail.

Installing Visual Studio

If you want to practice this book, you must install Visual Studio 2015, which provides everything you need to develop ASP. NET Core mvc. I am using the free version of Visual Studio Community and you can download it here in www.visualstudio.com. When installing, make sure that the Microsoft Web Web develooper Tools option is selected.

Tips: Visual Studio supports only the Windows platform, and on other platforms you can use Visual Studio Code to develop it, but it does not provide all the tools that are required for the sample program in this book, see Chapter 13th.

If you have already installed the Visual Studio, you must make sure that you are more aware of Visual Studio Update 3 because it provides support for ASP. If it is a new installation, the Update3 will be installed automatically. If you only need update, you can go to http://go.microsoft.com/fwlink/?linkId=691129 to download it here.

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

. That is, the newly installed Visual Studio, you also need to download. NET Core.

In the final step, you must download and install git, which can be downloaded here:https://git-scm.com/download.

Visual Studio contains his own version of Git, but it's not very useful and sometimes produces unpredictable things. For example, when used with other tools such as Bower. I'll tell you about Bower in the 6th chapter. When you install Git, tell the installer to add the tool to the PATH environment variable to make sure that visual Studio is able to find a new version of Git.

Figure 2-1, add git to path.

Start Visual Studio, select tools-> options, navigate to projects and solutions, expand Web Tools items, 2-2. Remove the Tick $ (vsinstalldir) \web\external\git to invalidate the version that comes with Visual Studio, but make sure that the $ (Path) entry is valid to use the version that you just installed.

figure 2-2 configuring Git in Visual Studio.

Build a new ASP. Net Core MVC Project (Project)

I will be in Create a new ASP. NET Core MVC project in Visual Studio. In Visual Studio, choose New Project from the menu to open the dialog box for the work. If you navigate to the Template->visual C#->web item in the left column, you will see the ASP. NET WEB Application project template, selected for this project type, shown in 2-3.

Figure 2-3 Visual Studio Core web App project template

tip : Selecting project templates can be a bit confusing, as they are several similar. Here's an explanation: ASP.

The Web application (. NET framework) template is used to build the project using the ASP., which is an earlier version of ASP. The other two templates are used to create an ASP. NET Core application, just using a different runtime library. You can choose between the. NET Framework and. NET Core. I will explain the difference between them in the 6th chapter. But I use the. NET core option in the entire book, so he is your only choice to make sure you run the example application to get the right results.

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

There are three of The ASP. NET Core template option, each using a different initial content to build a project. For this chapter, choose the Web Application option, which allows you to build an MVC application using predefined content to begin development.

Note : This is the only chapter that uses the Web App project template. I don't like pre-defined project templates because they encourage developers to treat important features like a black box, such as authentication. In this book, my goal is to let you understand and manage every aspect of the MVC application, so in later chapters in this book I use the empty template to start a project. In this chapter, I want you to get started quickly, this template is very suitable.

Click Change Authentication button, select the No Authentication option, 2-5. This project does not require authentication, but I'll show you how to secure an ASP. NET application in the 第28-30 chapter.

figure 2-5 selecting authentication settings

Click OK to close the Change Authentication dialog box. Make sure that the host in the Cloud is not selected, and then click OK to establish the Partyinvites project. Once visual Studio has finished creating the project, you will see some files and folders displayed in the Solution window, 2-6. This is the default structure for new MVC projects created using the Web Application template. You will soon be able to understand the role of each of these files and folders.

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

you can get from In the Debug menu, choose Start Debugging, (if it prompts you to turn on debugging, click the OK button), and you do so, Visual Studio compiles the raw cost application and then runs it with an application server called IIS, Then open the Web browser to request the content of the app, and you'll see the results below, 2-7.

Figure 2-7 running the example project

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

when you are done with these steps, if the browser displays an error message, close the browser window to stop debugging. Or go back to Visual Studio and select Stop Debugging in the Debug menu.

As you've just seen, Visual Studio opens the browser to display the project. You can select any browser you have installed in the Web browser menu by clicking on the right arrow of IIS Express and choosing a browser from the list of options. 2-8.

Figure 2-8 selecting a browser

starting from here, I'll use it in this book. Google Chrome or Google Chrome Canary to take a screenshot. But you can use any modern browser to display the examples in this book, including Microsoft Edge and the latest version of Internet Explorer.

Join Controller

in the In the MVC pattern, the incoming request is handled by the Controller, and in ASP. NET Core MVC, the controller is just a class, and the same city inherits from the built-in MVC controller base class Microsoft.AspNetCore.Mvc.Controller.

every public method in the controller is called an action. (action) method. It means that you can pass some URLs from the web on an action of English and French. In accordance with the traditional MVC conventions, the controller classes are generally placed in the Controllers folder, which was created by Visual Studio when the project was built.

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

Visual Studio has added the default controller class to the project, which you will see if you expand the Controllers folder in the Solution browser window. The default controller is called HomeController.cs. The controller class name is the end of the controllers, meaning that when you see the HomeController.cs file, you know he is a controller called home, and HomeController is the default controller for the MVC application. Click the HomeController.cs file you can edit it. You will see the code shown in list 2-1.

List 2-1. Initial content of the 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 ();

}

}

}

Use the following The contents of list 2-2 replace the original code in the HomeController.cs file. Here, I've only kept a method, changed the result type and his implementation, and removed those using statements that were not needed.

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 do not have a dynamic effect, but are a good demonstration. I have changed the index method to get him back to "Hello world". Now, click the Debug-Start debugging menu to run the project again.

tip : If and in the previous section to keep the application running, you need to choose the debugging-restart menu. Of course, if you want to, you choose to stop Debugging and then start debugging.

the browser will initiate a HTTP requests to the server. The default MVC configuration specifies that the request will be processed by the index method (called the action Method or action), and the result of the method will be sent back to the browser, as shown in 2-9.

Figure 2-9 the output of the Action method

Tip: Please note that the figure Visual Studio has pointed the browser to port 57628. You see that the URL port number on your browser is almost certainly different from the map. Because vs will randomly assign 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 VS, for delivering ASP. NET content and services at development time. In the 12th chapter, I will show you how to publish an MVC project to the production environment.

Understanding Routing

except Model,view and controllers, MVC applications also use the ASP. NET routing system, which contracts to determine how URLs are mapped to controller and action. A route is a rule that is used to determine such as and processing requests. When vs creates an MVC project, it adds some default routes for you. You can request the following URLs, which will 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 will return the result from the HomeController index method. You can try it yourself. Change the URL in the browser, assuming it is http://localhost:57628, if you add/home or/home/index after the URL and press ENTER, you will see the same hello World result.

This is a follow -up A good example of the conventions implemented by the ASP: I will have a controller called HomeController, which is the entry point for the MVC application. In the default VS configuration, when it is going to create a new MVC application, it assumes that we are following this Convention. Because I follow this convention, I will automatically support to the previous list, and if I do not follow this convention, I will have to modify the configuration to point to the other controller. For this simple example, the default configuration is what I need.

Rendering Web pages

the output from the preceding example is not HTML, he's just a simple "Hello world" string. To generate HTML for the 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 modify The Index action method, such as program 2-3. The changes I made were shown in bold fonts, and I used a convention that made 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 was from a When the action method returns a Viewresult object, I instruct MVC to render a view. I create a Viewresult object by calling the view method, which is called to make the name of the view MyView. If you run this application, you will find that MVC will try to find this view, and the error message shown in 2-10 will appear.

Figure 2-10 MVC tries to find a view

This error message is extremely helpful. It not only explains that MVC can't find the view I specified in the action method, but also tells me where to find it. All views are saved in the Views folder and organized into sub-folders. For example, the associated view in the Home controller is saved in a folder called Views/home. If a view does not have a fixed controller, it will be saved in the Views/shared folder. VS will create the home and shared folders when the Web Application template is used, and put in some placeholder view to enable the project to start.

to establish View, right-click Views->home in the Solution Explorer window and select Add-New Item in the pop-up menu. VS Sinks Show you some item templates, select the ASP. NET category in the left column and select the MVC View Page item in the middle column. 2-11.

Figure 2-11 Creating the View

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

Set the Name field Myview.cshtml then click the Add button to create the view. VS will create a views/home/myview.cshtml file and then open it for you to edit. Initially, the contents of the view file are just some comments and placeholders, please replace them with code 2-4.

Tip : It's easy to create a view file in the wrong folder, and if you don't end up creating myview.cshtml in Views/home, delete them and create them again.

Listing 2-4. Replace the contents of the myview.cshtml file

@{

Layout = null;

}

<! DOCTYPE html>

<meta name= "viewport" content= "Width=device-width"/>

<title>Index</title>

<body>

<div>

Hello World (from the view)

</div>

</body>

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

...

@{

Layout = null;

}

...

the new Most of the content in the view file is HTML, except for this part:

@{

Layout = null;

}

this is a An expression interpreted by the Razor view engine that processes the contents of the view and generates HTML that is sent back to the browser. This is a simple razor expression, and he will tell Razor that I chose not to use layout. Layout is an HTML template, and I'll explain it in the fifth chapter. I'll ignore razor and come back in a minute. 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 first edited When the Index action method returns a string, MVC will pass the string value to the browser, otherwise it will not do anything else. The index method now returns a VIEWRESULT,MVC renders a view (view) and returns the HTML it produces. I told MVC which view to use, so it uses a naming convention to find it automatically. The Convention is that the view has the same name as the action and is saved in a folder named after the controller.

in addition to strings and ViewResult, I can also have the action method return other types. For example, if I return a redirectresult, the browser will redirect to another URL. If I return a httpunauthorizedresult,i will force the user to log in. These objects are called the set control of action result. The action result system lets you encapsulate and reuse a generic action return. In chapter 17, I will introduce more relevant content.

Increase 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 into HTML.

one way to pass data from a controller to a view is to use the A ViewBag object that is a member of a controller base class. ViewBag is a dynamic object that you can assign to a view to render with any attribute. Code 2-5 demonstrates how to pass a simple object in a homecontroller.

Listing 2-5. Set up 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");

}

}

}

me to The Viewbag.greeting property is assigned a value to provide data to the view. The Greeting property does not exist before the assignment, which allows me to pass data from the controller to the view in an arbitrary and fluid manner without having to define the class before assigning the value. I referenced the Viewbag.greeting property in the view to get his value. As in code 2-6, this is the modified myview.cshtml.

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

@{

Layout = null;

}

<! DOCTYPE html>

<meta name= "viewport" content= "Width=device-width"/>

<title>Index</title>

<body>

<div>

@ViewBag. Greeting world (from the view)

</div>

</body>

the added part of the above code is The razor expression, which is evaluated when MVC uses a view to generate the appropriate value. When I call the View method inside the controller, MVC finds the myview.cshtml file and requests the Razor view engine to parse the contents of the file. Razor will look for an expression like the above code. In this case, the processing expression means inserting the Viewbag.greeting property into the view.

Greeting this attribute name is nothing special, you can use any other name, and it works just as well. As long as your name in the controller is the same as the name in the view. You can use multiple properties to pass multiple data. Then you run a look at the effect, 2-13.

Figure 2-13 Dynamic response of an MVC

Pro ASP. NET Core MVC version 6th chapter II (first half chapter)

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.