006. Adding a controller to a ASP. NET Core MVC app with Visual Studio, 006. addingmvc

Source: Internet
Author: User

006. Adding a controller to a ASP. NET Core MVC app with Visual Studio, 006. addingmvc

Adding a controller to a ASP. NET Core MVC app with Visual Studio

Add a controller to asp.net core mvc.

By Rick Anderson

The Model-View-Controller (MVC) implements tural pattern separates an app into three main components:MOdel,VIew, andCOntroller.

The MVC schema divides the program into three components:MOdelVIewCOntroller.

The MVC pattern helps you create apps that are more testable and easier to update than traditional monolithic apps. MVC-based

Compared with the traditional Integrated Program, the MVC mode helps you build programs that are easier to test and upgrade.

Apps contain:

MVC-based programs include:

  • MOdels: Classes that represent the data of the app. The model classes use validation logic to enforce business rules for that

MOdels: class used to represent app data. The model class contains the logic used to verify business data rules.

Data. Typically, model objects retrieve and store model state in a database. In this tutorial, a Movie model retrieves movie

Typically, model objects access data in databases. In this tutorial, Movie is used to obtain data from the database,

Data from a database, provides it to the view or updates it. Updated data is written to a database.

Provided to the view or used for db updates. The updated data is written into the database.

  • VIews: Views are the components that display the app's user interface (UI). Generally, this UI displays the model data.

VIews: view is a component used to display the app ui. Normally, the ui displays data in the model.

  • COntrollers: Classes that handle browser requests. They retrieve model data and call view templates that return a response. In

COntrollers: the controller is a class used to process browser requests. They obtain the data in the model, process the view template, and respond to the browser.

An MVC app, the view only displays information; the controller handles and responds to user input and interaction.

In mvc applications, views are only used to display information. The controller processes and responds to user input and interaction.

Example, the controller handles route data and query-string values, and passes these values to the model. The model might

For example, the controller processes the routing data and "? Param = xxxx.

Use these values to query the database. For example, http: // localhost: 1234/Home/About has route data of Home (

The model can use the data to query the database. For example, http: // localhost: 1234/Home/About contains route data, home (Controller ),

Controller) and About (the action method to call on the home controller). http: // localhost: 1234/Movies/Edit/5 is

About (action method ). Http: // localhost: 1234/Movies/Edit/5 is

Request to edit the movie with ID = 5 using the movie controller. We'll talk about route data later in the tutorial.

Request to edit the url with id = 5. We will discuss routing data later in the tutorial.

The MVC pattern helps you create apps that separate the different aspects of the app (input logic, business logic, and UI logic ),

The MVC pattern helps the app to focus on and separate different aspects, such as the input logic, business logic, UI logic,

While providing a loose coupling between these elements. The pattern specifies where each kind of logic shocould be located in

It can provide a loosely coupled structure in these aspects. The Mvc mode specifies the specific location of each type of logic in the app.

App. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation

The UI Logic belongs to the view. The input Logic belongs to the Controller. The Business Logic belongs to the data model.

Helps you manage complexity when you build an app, because it enables you to work on one aspect of the implementation at

This separation helps you manage complex applications, because it helps you focus only on one aspect of implementation instead

Time without impacting the code of another. For example, you can work on the view code without depending on the business logic

Consider the impact of another factor. For example, you can write debugging code on the view without relying on the business logic code.

Code.

We cover these concepts in this tutorial series and show you how to use them to build a movie app. The MVC project contains

This concept runs through the entire tutorial and will teach you how to use them to build a movie app. An mvc project contains

Folders forControllersAndViews.ModelsFolder will be added in a later step.

ControllersAndViewsFolder.ModelsThe folder will be added in the subsequent steps.

  • InSolution Explorer, Right-clickControllers> Add> New Item

In resource manager, right-click Controllers> Add> New Item menu

 

  • SelectMVC Controller Class

SelectMVC Controller ClassOption

  • InAdd New ItemDialog, enterHelloWorldController.

InAdd New ItemDialog box, enterHelloWorldController.

 

Replace the contentsControllers/HelloWorldController. csWith the following:

InControllers/HelloWorldController. cs, Enter the following code:

1 using Microsoft. aspNetCore. mvc; 2 3 using System. text. encodings. web; 4 5 6 7 namespace MvcMovie. controllers 8 9 {10 11 public class HelloWorldController: Controller12 13 {14 15 // 16 17 // GET:/HelloWorld/18 19 20 21 public string Index () 22 23 {24 25 return "This is my default action... "; 26 27} 28 29 30 31 // 32 33 // GET:/HelloWorld/Welcome/34 35 36 37 public string Welcome () 38 39 {40 41 return "This is the Welcome action method... "; 42 43} 44 45} 46 47}C # code

Every public method in a controller is callable as an HTTP endpoint. In the sample above, both methods return a string. Note

Each public-modified method in the controller can be requested by http. In the preceding example, both methods return a string.

Comments preceding each method.

An HTTP endpoint is a targetable URL in the web application, such as http: // localhost: 1234/HelloWorld, and combines

An http endpoint is a url that can be hit in a browser, such as http: // localhost: 1234/HelloWorld,

Protocol used: HTTP, the network location of the web server (including the TCP port): localhost: 1234 and the target

It contains the http protocol prefix (http), tcp address (localhost: 1234), and uri (HelloWorld ).

URI HelloWorld.

The first comment states this is an http get method that is invoked by appending "/HelloWorld/" to the base URL. The second

The first comment indicates that this method is an http get method. It can be called by adding/HelloWorld/to the base URL. Second comment

Comment specifies an http get method that is invoked by appending "/HelloWorld/Welcome/" to the URL. Later on in the tutorial

This is also an http get method. It can be called by adding/HelloWorld/Welcome/to the base URL. Later in this tutorial

You'll use the scaffolding engine to generate http post methods.

You will learn to use the base frame engine to produce the http post method.

Run the app in non-debug mode and append "HelloWorld" to the path in the address bar. The Index method returns a string.

Run the app in non-debug mode and append HelloWorld to the address bar. The Index method is called and returns a string.

 

MVC invokes controller classes (and the action methods within them) depending on the incoming URL.

The MVC call controller class depends on the requested URL.

The default URL routing logic used by MVC uses a format like this to determine what code to invoke:

The default URL routing rules determine how MVC calls controller code in a format similar to the following:

/[Controller]/[ActionName]/[Parameters]

Routing rule string

You set the format for routing inStartup. csFile.

You needStartup. csFile, set routing rules.

1 app. useMvc (routes => 2 3 {4 5 routes. mapRoute (6 7 name: "default", 8 9 template: "{controller = Home}/{action = Index}/{id ?} "); 10 11 });C # code

When you run the app and don't supply any URL segments, it defaults to the "Home" controller and the "Index" method specified in

When you run the app without providing URL segments, the program calls the home controller by default and runs the index method.

The template line highlighted above.

The first URL segment determines the controller class to run. So localhost: xxxx/HelloWorld maps

The first URL segment determines that the controller class is executed. Therefore, localhost: xxxx/HelloWorld maps

The HelloWorldController class. The second part of the URL segment determines the action method on the class.

HelloWorldController. The second URL segment determines which method in the controller is executed.

So localhost: xxxx/HelloWorld/Index wocould cause the Index method of the HelloWorldController class to run. Notice

Therefore, the url localhost: xxxx/HelloWorld/Index will cause the Index method in the HelloWorldController class to be executed.

That you only had to browse to localhost: xxxx/HelloWorldand the Index method was called by default. This is

Note that you only request localhost: xxxx/HelloWorld in the browser, and the Index method is called by default.

Because Index is the default method that will be called on a controller if a method name is not explicitly specified. The third part

This is because when the method of a controller is not explicitly specified, the index is the default method.

Of the URL segment (id) is for route data. You'll see route data later on in this tutorial.

The third part of the URL segment, id is a route data. Later in this tutorial, you will understand route data.

Browse to http: // localhost: xxxx/HelloWorld/Welcome. The Welcome method runs and returns the string "This is

Browse http: // localhost: xxxx/HelloWorld/Welcome. the Welcome method is executed and the return string "This is the..." is returned ...".

Welcome action method... ". For this URL, the controller is HelloWorld and Welcomeis the action method. You haven't used

For this URL, the controller is HelloWorld, and the action is the Welcome method.

The [Parameters] part of the URL yet.

So far, you have not used the [Parameters] section of the URL segment.

 

Modify the code to pass some parameter information from the URL to the controller.

Modify the code and pass some parameters to the Controller through the URL.

Example,/HelloWorld/Welcome? Name = Rick & numtimes = 4. Change the Welcome method to include two parameters as shown in

For example,/HelloWorld/Welcome? Name = Rick & numtimes = 4. Change the Welcome method like the following code to include two parameters.

The following code.

1 // GET:/HelloWorld/Welcome/2 3 // Requires using System. text. encodings. web; 4 5 public string Welcome (string name, int numTimes = 1) 6 7 {8 9 return HtmlEncoder. default. encode ($ "Hello {name}, NumTimes is: {numTimes}"); 10 11}C # code

The preceding code:

Previous Code:

  • Uses the C # optional-parameter feature to indicate that the numTimes parameter defaults to 1 if no value is passed for that

Because the C # optional parameter feature is used, when the numTimes parameter is not specified, its value is 1 by default.

Parameter.

  • UsesHtmlEncoder. Default. Encode to protect the app from malicious input (namely JavaScript ).

The HtmlEncoder. Default. Encode method can be used to prevent malicious input attacks.

  • Uses Interpolated Strings.

Use the string interpolation syntax.

Run your app and browse:

Run your app and navigate to the following URL:

Http: // localhost: xxxx/HelloWorld/Welcome? Name = Rick & numtimes = 4

(Replace xxxx with your port number.) You can try different values for name and numtimes in the URL.

(Replace xxxx with your own port) You can try the parameter values that are not allowed in the URL.

The MVC model binding system automatically maps the named parameters from the query string in the address bar to parameters

The MVC model binding automatically maps the value of the named parameter in the URL to the parameter corresponding to the method and assigns a value.

In your method. See Model Binding for more information.

You can view the model binding for more information.

 

In the image above, the URL segment (Parameters) is not used, the name and numTimes parameters are passed as query strings.

In, the parameter section of the URL segment is not used, and the parameter name and numTimes are passed to the background in the form of a query string.

The? (Question mark) in the above URL is a separator, and the query strings follow. The & character separates query strings.

? Is a query separator followed by parameters. Each parameter is separated by a symbol.

Replace the Welcome method with the following code:

Use the following code to replace the Welcome method:

1 public string Welcome (string name, int ID = 1) 2 3 {4 5 return HtmlEncoder. default. encode ($ "Hello {name}, ID: {ID}"); 6 7}C # code

Run the app and enter the following URL: http: // localhost: xxx/HelloWorld/Welcome/3? Name = Rick

Run the app and enter the address: (the url above)

 

This time the third URL segment matched the route parameter id. The Welcome method contains a parameter id that matched

This URL segment matches the route parameter id. The Welcome method contains an id parameter and is matched.

The URL template in the MapRoute method. The trailing? (In id ?) Indicates the id parameter is optional.

The URL template is in the MapRoute method. Tail? Id is an optional parameter.

1 app. useMvc (routes => 2 3 {4 5 routes. mapRoute (6 7 name: "default", 8 9 template: "{controller = Home}/{action = Index}/{id ?} "); 10 11 });C # code

In these examples the controller has been doing the "VC" portion of MVC-that is, the view and controller work. The controller is

In these examples, we have used V and C in MVC.

Returning HTML directly. Generally you don't want controllers returning HTML directly, since that becomes very cumbersome

The Controller returns html directly. However, we usually do not use the Controller to directly return HTML because it makes code maintenance very cumbersome.

Code and maintain. Instead you typically use a separate Razor view template file to help generate the HTML response.

Instead, we will use a Razor view template to generate HTML responses.

You do that in the next tutorial.

You will do this in subsequent tutorials.

In Visual Studio, in non-debug mode (Ctrl + F5), you don't need to build the app after changing code. Just save the file, refresh your

In VS, in non-debug mode, when the code changes, you do not need to re-compile the code, just save the file, and then,

Browser and you can see the changes.

Refresh your browser to see the new changes.

 

Mon

Thursday

 

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.