Getting started with ASP.NET Core MVC and Visual Studio
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
Movie
model 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 Welcome action method...";
}
}
}
Every public
method 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 POST
methods.
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 method
returns 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/HelloWorld
maps to the HelloWorldController
class.
The second part of the URL segment determines the action method on the class.
So localhost:xxxx/HelloWorld/Index
would cause the Index
method of theHelloWorldController
class to run.
Notice that we only had to browse to localhost:xxxx/HelloWorld
and the Index
method was called by default.
This is because Index
is 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 Welcome
method runs and returns the string “This is the Welcome action method...”.
The default MVC routing is/[Controller]/[ActionName]/[Parameters]
.
For this URL, the controller is HelloWorld
and Welcome
is 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 Welcome
method to include two parameters as shown below.
Note that the code uses the C# optional-parameter feature to indicate that the numTimes
parameter defaults to 1 if no value is passed for that parameter.
public string Welcome(string name, int numTimes = )
{
return HtmlEncoder.Default.Encode(
"Hello " + name + ", NumTimes is: " + numTimes);
}
The code above uses HtmlEncoder.Default.Encode
to 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 name
and numtimes
in 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 name
and numTimes
parameters 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 Welcome
method with the following code:
public string Welcome(string name, int Id = )
{
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 Welcome
method contains a parameter id
that matched the URL template in the MapRoute
method.
The trailing ?
(in id?
) indicates the id
parameter 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.
Getting started with ASP.NET Core MVC and Visual Studio的更多相关文章
- ASP.NET Core 中文文档 第二章 指南(4.1)ASP.NET Core MVC 与 Visual Studio 入门
原文:Getting started with ASP.NET Core MVC and Visual Studio 作者:Rick Anderson 翻译:娄宇(Lyrics) 校对:刘怡(Alex ...
- 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】
Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...
- 004.Create a web app with ASP.NET Core MVC using Visual Studio on Windows --【在 windows上用VS创建mvc web app】
Create a web app with ASP.NET Core MVC using Visual Studio on Windows 在 windows上用VS创建mvc web app 201 ...
- 005.Getting started with ASP.NET Core MVC and Visual Studio -- 【VS开发asp.net core mvc 入门】
Getting started with ASP.NET Core MVC and Visual Studio VS开发asp.net core mvc 入门 2017-3-7 2 分钟阅读时长 本文 ...
- ASP.NET Core MVC和Visual Studio入门
本教程将教你使用Visual Studio 2017创建 ASP.NET Core MVC web应用程序的基础知识. 安装Visual Studio 2017 和.Net Core 安装Visual ...
- 【Asp.Net Core】在Visual Studio 2017中使用Asp.Net Core构建Angular4应用程序
前言 Visual Studio 2017已经发布了很久了.做为集成了Asp.Net Core 1.1的地表最强IDE工具,越来越受.NET系的开发人员追捧. 随着Google Angular4的发布 ...
- ASP.NET Core 中文文档 第二章 指南(2)用 Visual Studio 和 ASP.NET Core MVC 创建首个 Web API
原文:Building Your First Web API with ASP.NET Core MVC and Visual Studio 作者:Mike Wasson 和 Rick Anderso ...
- 创建ASP.NET Core MVC应用程序(1)-添加Controller和View
创建ASP.NET Core MVC应用程序(1)-添加Controller和View 参考文档:Getting started with ASP.NET Core MVC and Visual St ...
- ASP.NET Core MVC/WebAPi 模型绑定探索
前言 相信一直关注我的园友都知道,我写的博文都没有特别枯燥理论性的东西,主要是当每开启一门新的技术之旅时,刚开始就直接去看底层实现原理,第一会感觉索然无味,第二也不明白到底为何要这样做,所以只有当你用 ...
随机推荐
- Vue2-Editor 使用
Vue-Editor底层采取的是quill.js,而quill.js采用的是html5的新属性classList,所以版本低于ie10会报错“无法获取未定义或 null 引用的属性‘confirm’” ...
- mysql 导入数据库时,报错1840的解决方法
1.现象 在mysql用sql文件导入数据库时,提示ERROR 1840 (HY000) at line 24: @@GLOBAL.GTID_PURGED can only be set when @ ...
- JavaScript的基本语法(一)
一.常用的表单元素有: 文本框(text). 密码框(password). 多行文本框(<textarea>) 单选按钮(radio). 复选框(checkbox). 列表框(<se ...
- java Web(2)
Servlet与web容器的配合: 1)客户端向Web服务器发起一个HTTP请求. 2)HTTP请求被Web服务器接受,如果请求的是静态页面,则由Web服务器负责处理.如果请求的是Java Web组件 ...
- AI: DL方法与问题空间探索
所谓问题的解决是生存参数空间的一种状态转移到另外一种状态,而目的状态恰好是主体所希望的.完成这种转换的一系列脚本变化过程叫做场景序列,也叫通路.驱动这一些列场景转换的主体参与过程,被称为主动执行.而主 ...
- 集合运算(UNION)
表的加法 集合运算:就是满足统一规则的记录进行的加减等四则运算. 通过集合运算可以得到两张表中记录的集合或者公共记录的集合,又或者其中某张表中记录的集合. 集合运算符:用来进行集合的运算符. UNIO ...
- Android 性能测试初探(一)
Android 性能测试,跟 pc 性能测试一样分为客户端及服务器,但在客户端上的性能测试分为 2 类: 一类为 rom 版本的性能测试 一类为应用的性能测试 对于应用性能测试,包括很多测试项,如启动 ...
- 记录:Ubuntu下升级Python从2.x到3.x
一.安装Python3 在Ubuntu中的终端输入:sudo apt-get install python3 提示资源被锁住,可能有另外一个程序在占用此资源. 解决方法:输入以下指令解锁资源 sudo ...
- 怎么获取自定义核算项目里某一个类型的数据:做f7
在BOS里加一个F7字段,关联物料或其他可以选到的基础资料.保存后先别发布 切换到BOS透视图,打到对应的.relation文件,修改supplierEntity,原来是指定物料的实体,改成自定 ...
- eas更改用户组织范围和业务组织范围
表: T_PM_OrgRangeIncludeSubOrg 10 20 30 分别代表 业务组织 行政组织 以及管辖组织.查行政组织,