Getting started with ASP.NET Core MVC and Visual Studio
2016-06-14 17:00
337 查看
This tutorial will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio 2015.
https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html
https://docs.asp.net/en/latest/tutorials/first-mvc-app/adding-controller.html
The Model-View-Controller (MVC) architectural pattern separates an app into three main components: the Model, the View, and the Controller.
The MVC pattern helps you create apps that are testable and easier to maintain and update than traditional monolithic apps. MVC-based apps contain:
Models: Classes that represent the data of the app and that use validation logic to enforce business rules for that data. Typically, model objects retrieve and store model state in a database. In this tutorial, a
Views: Views are the components that display the app’s user interface (UI). Generally, this UI displays the model data.
Controllers: Classes that handle browser requests, retrieve model data, and then specify view templates that return a response to the browser. In an MVC app, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles route data and query-string values, and passes these values to the model. The model might use these values to query the database.
The MVC pattern helps you create apps that separate the different aspects of the app (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
The pattern specifies where each kind of logic should be located in the app.
The UI logic belongs in the view.
Input logic belongs in the controller.
Business logic belongs in the model.
This separation helps you manage complexity when you build an app, because it enables you to work on one aspect of the implementation at a time without impacting the code of another.
For example, you can work on the view code without depending on the business logic code.
We’ll be covering all these concepts in this tutorial series and show you how to use them to build a simple movie app.
The following image shows the Models, Views and Controllers folders in the MVC project.
In Solution Explorer, right-click Controllers > Add > Controller...
In the Add Scaffold dialog
Tap MVC Controller - Empty
Tap Add
Name the controller HelloWorldController
Tap Add
Replace the contents of Controllers/HelloWorldController.cs with the following:
Every
The first comment states this is an HTTP GET method that is invoked by appending “/HelloWorld/” to the URL.
The second comment specifies an HTTP GET method that is invoked by appending “/HelloWorld/Welcome/” to the URL.
Later on in the tutorial we’ll use the scaffolding engine to generate
Run the app in non-debug mode (press Ctrl+F5) and append “HelloWorld” to the path in the address bar.
(In the image below, http://localhost:1234/HelloWorld is used, but you’ll have to replace 1234with the port number of your app.)
The
MVC invokes controller classes (and the action methods within them) depending on the incoming URL.
The default URL routing logic used by MVC uses a format like this to determine what code to invoke:
/[Controller]/[ActionName]/[Parameters]
You set the format for routing in the Startup.cs file.
When you run the app and don’t supply any URL segments, it defaults to the “Home” controller and the “Index” method specified in the template line highlighted above.
The first URL segment determines the controller class to run.
So
The second part of the URL segment determines the action method on the class.
So
Notice that we only had to browse to
This is because
The third part of the URL segment (
We’ll see route data later on in this tutorial.
Browse to
The
The default MVC routing is
For this URL, the controller is
We haven’t used the
Let’s modify the example slightly so that you can pass some parameter information from the URL to the controller (for example,
Change the
Note that the code uses the C# optional-parameter feature to indicate that the
The code above uses
In Visual Studio 2015, when you are running without debugging (Ctl+F5), you don’t need to build the app after changing the code.
Just save the file, refresh your browser and you can see the changes.
Run your app and browse to:
http://localhost:63126/HelloWorld/Welcome?name=chucklu&numtimes=2
(Replace xxxx with your port number.)
You can try different values for
The MVC model binding system automatically maps the named parameters from the query string in the address bar to parameters in your method.
See Model Binding for more information.
In the sample above, the URL segment (
The
Replace the
Run the app and enter the following URL
http://localhost:63126/HelloWorld/Welcome/3?name=chucklu
需要特别注意的是,这次是直接在Welcome后面加了/3? ,然后才附加了name
This time the third URL segment matched the route parameter
The
The trailing
In these examples the controller has been doing the “VC” portion of MVC - that is, the view and controller work.
The controller is returning HTML directly.
Generally you don’t want controllers returning HTML directly, since that becomes very cumbersome笨重,累赘 to code and maintain.
Instead we’ll typically use a separate Razor view template file to help generate the HTML response. We’ll do that in the next tutorial.
https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html
https://docs.asp.net/en/latest/tutorials/first-mvc-app/adding-controller.html
The Model-View-Controller (MVC) architectural pattern separates an app into three main components: the Model, the View, and the Controller.
The MVC pattern helps you create apps that are testable and easier to maintain and update than traditional monolithic apps. MVC-based apps contain:
Models: Classes that represent the data of the app and that use validation logic to enforce business rules for that data. Typically, model objects retrieve and store model state in a database. In this tutorial, a
Moviemodel retrieves movie data from a database, provides it to the view or updates it. Updated data is written to a SQL Server database.
Views: Views are the components that display the app’s user interface (UI). Generally, this UI displays the model data.
Controllers: Classes that handle browser requests, retrieve model data, and then specify view templates that return a response to the browser. In an MVC app, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles route data and query-string values, and passes these values to the model. The model might use these values to query the database.
The MVC pattern helps you create apps that separate the different aspects of the app (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
The pattern specifies where each kind of logic should be located in the app.
The UI logic belongs in the view.
Input logic belongs in the controller.
Business logic belongs in the model.
This separation helps you manage complexity when you build an app, because it enables you to work on one aspect of the implementation at a time without impacting the code of another.
For example, you can work on the view code without depending on the business logic code.
We’ll be covering all these concepts in this tutorial series and show you how to use them to build a simple movie app.
The following image shows the Models, Views and Controllers folders in the MVC project.
In Solution Explorer, right-click Controllers > Add > Controller...
In the Add Scaffold dialog
Tap MVC Controller - Empty
Tap Add
Name the controller HelloWorldController
Tap Add
Replace the contents of Controllers/HelloWorldController.cs with the following:
using Microsoft.AspNetCore.Mvc; using System.Text.Encodings.Web; namespace MvcMovie.Controllers { public class HelloWorldController : Controller { // // GET: /HelloWorld/ public string Index() { return "This is my default action..."; } // // GET: /HelloWorld/Welcome/ public string Welcome() { return "This is the Welcomeaction method..."; } } }
Every
publicmethod in a controller is callable as an HTTP endpoint. In the sample above, both methods return a string. Note the comments preceding each method:
The first comment states this is an HTTP GET method that is invoked by appending “/HelloWorld/” to the URL.
The second comment specifies an HTTP GET method that is invoked by appending “/HelloWorld/Welcome/” to the URL.
Later on in the tutorial we’ll use the scaffolding engine to generate
HTTP POSTmethods.
Run the app in non-debug mode (press Ctrl+F5) and append “HelloWorld” to the path in the address bar.
(In the image below, http://localhost:1234/HelloWorld is used, but you’ll have to replace 1234with the port number of your app.)
The
Index methodreturns a string. You told the system to return some HTML, and it did!
MVC invokes controller classes (and the action methods within them) depending on the incoming URL.
The default URL routing logic used by MVC uses a format like this to determine what code to invoke:
/[Controller]/[ActionName]/[Parameters]
You set the format for routing in the Startup.cs file.
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
When you run the app and don’t supply any URL segments, it defaults to the “Home” controller and the “Index” method specified in the template line highlighted above.
The first URL segment determines the controller class to run.
So
localhost:xxxx/HelloWorldmaps to the
HelloWorldControllerclass.
The second part of the URL segment determines the action method on the class.
So
localhost:xxxx/HelloWorld/Indexwould cause the
Indexmethod of the
HelloWorldControllerclass to run.
Notice that we only had to browse to
localhost:xxxx/HelloWorldand the
Indexmethod was called by default.
This is because
Indexis the default method that will be called on a controller if a method name is not explicitly specified.
The third part of the URL segment (
Parameters) is for route data.
We’ll see route data later on in this tutorial.
Browse to
http://localhost:xxxx/HelloWorld/Welcome.
The
Welcomemethod runs and returns the string “This is the Welcomeaction method...”.
The default MVC routing is
/[Controller]/[ActionName]/[Parameters].
For this URL, the controller is
HelloWorldand
Welcomeis the action method.
We haven’t used the
[Parameters]part of the URL yet.
Let’s modify the example slightly so that you can pass some parameter information from the URL to the controller (for example,
/HelloWorld/Welcome?name=Scott&numtimes=4).
Change the
Welcomemethod to include two parameters as shown below.
Note that the code uses the C# optional-parameter feature to indicate that the
numTimesparameter defaults to 1 if no value is passed for that parameter.
public string Welcome(string name, int numTimes = 1) { return HtmlEncoder.Default.Encode( "Hello " + name + ", NumTimes is: " + numTimes); }
The code above uses
HtmlEncoder.Default.Encodeto protect the app from malicious恶意的 input (namely也就是 JavaScript).
In Visual Studio 2015, when you are running without debugging (Ctl+F5), you don’t need to build the app after changing the code.
Just save the file, refresh your browser and you can see the changes.
Run your app and browse to:
http://localhost:63126/HelloWorld/Welcome?name=chucklu&numtimes=2
(Replace xxxx with your port number.)
You can try different values for
nameand
numtimesin the URL.
The MVC model binding system automatically maps the named parameters from the query string in the address bar to parameters in your method.
See Model Binding for more information.
In the sample above, the URL segment (
Parameters) is not used, the
nameand
numTimesparameters are passed as query strings.
The
?(question mark) in the above URL is a separator, and the query strings follow. The
&character separates query strings.
Replace the
Welcomemethod with the following code:
public string Welcome(string name, int Id = 1) { return HtmlEncoder.Default.Encode( "Hello " + name + ", Id: " + Id); }
Run the app and enter the following URL
http://localhost:63126/HelloWorld/Welcome/3?name=chucklu
需要特别注意的是,这次是直接在Welcome后面加了/3? ,然后才附加了name
This time the third URL segment matched the route parameter
id.
The
Welcomemethod contains a parameter
idthat matched the URL template in the
MapRoutemethod.
The trailing
?(in
id?) indicates the
idparameter is optional.
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
In these examples the controller has been doing the “VC” portion of MVC - that is, the view and controller work.
The controller is returning HTML directly.
Generally you don’t want controllers returning HTML directly, since that becomes very cumbersome笨重,累赘 to code and maintain.
Instead we’ll typically use a separate Razor view template file to help generate the HTML response. We’ll do that in the next tutorial.
相关文章推荐
- ASP.NET vs MVC vs WebForms
- [转]Membership 到 .NET4.5 之 ASP.NET Identity
- 转: KindEditor 图片空间文件增加删除文件、文件夹功能(ASP语言环境)
- ASP.NET错误处理的三种方式
- [转]Asp.net MVC 利用PartialView 构造自定义菜单
- asp.net Framework 与 asp.net core 知识
- 在raspberry运行xibo
- asp.net web forms和asp.net mvc比较
- asp.net webpage
- BrnShop开源网上商城第二讲:ASP.NET MVC框架
- 比较分析 Spring AOP 和 AspectJ 之间的差别
- [转]ASP.NET 成员资格 Part.1(API)
- Spring AOP @AspectJ进阶
- 注意!ASP.NET MVC 3 的一个 OutputCache 问题
- ASP.net 中 OutputCache 指令各个参数的作用
- 理解SVG坐标系和变换:视窗,viewBox和preserveAspectRatio
- asp.net MVC 应用程序的生命周期
- ASP.NET生命周期详解 [转]
- asp.net core
- asp.net web开发所用到的技术