007.Adding a view to an ASP.NET Core MVC app — 【在asp.net core mvc中添加视图】

Adding a view to an ASP.NET Core MVC app

在asp.net core
mvc中添加视图

2017-3-4 7 分钟阅读时长 

本文内容

1.Changing views and layout
pages

修改视图和布局页

2.Change the title and menu link in the layout
file

在布局文件中修改标题与菜单

3.Passing Data from the Controller to the
View

从控制器向视图传递数据

By Rick Anderson

In this section you modify the HelloWorldController class to use Razor
view template files to cleanly encapsulate the process of

在本节中,你将学会在
HelloWorldController 中行使Razor
视图模板文件来根本的拍卖并生成一个HTML响应并

generating HTML responses to a client.

传送到浏览器。

You create a view template file using Razor. Razor-based view templates
have a .cshtml file extension. They provide an elegant way

应用Razor创制一个视图模板文件。基于Razor的视图模板的公文扩充名是.cshtml
。他提供了一个简洁的法子

to create HTML output using C#.

使用C#来创建HTML输出。

Currently the Index method returns a string with a message that is
hard-coded in the controller class.

当前 Index
方法重返一个在控制器中硬编码的字符串。

In the HelloWorldController class, replace the Index method with the
following code:

用下边的代码替换
HelloWorldController 类中 Index 方法中的代码:

图片 1图片 2

1 public IActionResult Index()
2 
3 {
4 
5     return View();
6 
7 }

C# code

The preceding code returns a View object. It uses a view template to
generate an HTML response to the browser.

前述代码再次回到了一个 View
对象。他会使用一个视图模板生成HTML并响应到浏览器。

Controller methods (also known as action methods) such as
the Index method above,

像下边的 Index
方法就是一个控制器方法(也就是我们说的 action 方法),

generally return
an IActionResult (or
a class derived from ActionResult), not primitive types like string.

普普通通,不会回去一个像string这样的原始类型,而是IActionResult
或者一个继承自ActionResult 的类。

  • Right click on the Views folder, and then Add > New
    Folder
     and name the folder HelloWorld.

右击Views 文件夹,然后点击Add
> New Folder
菜单,并将文件夹命名为HelloWorld

  • Right click on the Views/HelloWorld folder, and then Add >
    New Item
    .

右击 Views/HelloWorld
文件夹,然后点击Add > New Item 菜单。

  • In the Add New Item – MvcMovie dialog

Add New Item – MvcMovie
对话框中

  • In the search box in the upper-right, enter view

在右上角的查找框中,输入
view

  • Tap MVC View Page

点击 MVC View Page
选项

  • In the Name box, change the name if necessary to Index.cshtml.

Name 框中,修改名字为
Index.cshtml

  • Tap Add

点击 Add

 图片 3

Replace the contents of the Views/HelloWorld/Index.cshtml Razor view
file with the following:

采纳上面的代码替换
Views/HelloWorld/Index.cshtml  文件中的代码:

图片 4图片 5

 1 @{
 2 
 3     ViewData["Title"] = "Index";
 4 
 5 }
 6 
 7  
 8 
 9 <h2>Index</h2>
10 
11  
12 
13 <p>Hello from our View Template!</p>

HTML code

Navigate to http://localhost:xxxx/HelloWorld. The Index method in
the HelloWorldControllerdidn’t do much;

导航到
http://localhost:xxxx/HelloWorld 。控制器中的 Index
方法没有做太多事情;

it ran the statement return View();,

她实施了语句 return View();

which specified that the method should use a view template file to
render a response to the browser.

它指定了法子运用一个视图文件来渲染并扭转发送给浏览器的响应。

Because you didn’t explicitly specify the name of the view template
file,

因为你不需要明确的指定视图模板文件的名字,

MVC defaulted to using the Index.cshtml view file in
the /Views/HelloWorld folder.

MVC默认会接纳 在
/Views/HelloWorld  这些文件夹下的 Index.cshtml 视图文件。

The image below shows the string “Hello from our View Template!”
hard-coded in the view.

下图显示了被硬编码在视图文件中的字符串“Hello
from our View Template!” 。

图片 6

If your browser window is small (for example on a mobile device),

只要您在一个很小的窗口上浏览,如手机上,

you might need to toggle (tap) the Bootstrap navigation
button
 in the upper right
to see the HomeAbout, and Contact links.

您或许需要点击右上角的领航菜单才能见到
HomeAbout,  Contact  链接。

 图片 7

Changing views and layout pages

修改视图与布局页

Tap the menu links (MvcMovieHomeAbout). Each page shows
the same menu layout.

点击菜单上的两样链接。每个页面都会展现均等的布局。

The menu layout is implemented in
the Views/Shared/_Layout.cshtml file. Open
the Views/Shared/_Layout.cshtml file.

食谱布局在
Views/Shared/_Layout.cshtml 文件中贯彻。打开这一个文件。

Layout templates
allow you to specify the HTML container layout of your site in one place
and then apply it across multiple pages in your site.

Layout
模板能够使您在一个地点布局一定的html然后在你站点的六个页面上出示同一的内容与表现。

Find the @RenderBody() line. 

找到 @RenderBody()
这一行。

RenderBody is a placeholder where all the view-specific pages you create
show up, wrapped in the layout page.

RenderBody
是一个占位符,所有你成立的一定的视图页在布局页中涵盖在内。

For example, if you select the About link,
the Views/Home/About.cshtml view is rendered inside
the RenderBody method.

诸如,若果你点击了 About
链接 ,Views/Home/About.cshtml 文件将会在 RenderBody
方法中渲染呈现。

Change the title and menu link in the layout file

在布局页中修改标题与菜单链接

Change the contents of the title element.

修改标题内容。

Change the anchor text in the layout template to “Movie App” and the
controller from Home to Movies as highlighted below:

修改链接的文件在布局模板中,如下高亮部分所示:

图片 8图片 9

  1 @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
  2 
  3 <!DOCTYPE html>
  4 
  5 <html>
  6 
  7 <head>
  8 
  9     <meta charset="utf-8" />
 10 
 11     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 12 
 13     <title>@ViewData["Title"] - Movie App</title>
 14 
 15  
 16 
 17     <environment names="Development">
 18 
 19         <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
 20 
 21         <link rel="stylesheet" href="~/css/site.css" />
 22 
 23     </environment>
 24 
 25     <environment names="Staging,Production">
 26 
 27         <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
 28 
 29               asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
 30 
 31               asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
 32 
 33         <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
 34 
 35     </environment>
 36 
 37     @Html.Raw(JavaScriptSnippet.FullScript)
 38 
 39 </head>
 40 
 41 <body>
 42 
 43     <nav class="navbar navbar-inverse navbar-fixed-top">
 44 
 45         <div class="container">
 46 
 47             <div class="navbar-header">
 48 
 49                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
 50 
 51                     Toggle navigation
 52 
 53                     
 54 
 55                     
 56 
 57                     
 58 
 59                 </button>
 60 
 61                 <a asp-area="" asp-controller="Movies" asp-action="Index" class="navbar-brand">MvcMovie</a>
 62 
 63             </div>
 64 
 65             <div class="navbar-collapse collapse">
 66 
 67                 <ul class="nav navbar-nav">
 68 
 69                     <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
 70 
 71                     <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
 72 
 73                     <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
 74 
 75                 </ul>
 76 
 77             </div>
 78 
 79         </div>
 80 
 81     </nav>
 82 
 83     <div class="container body-content">
 84 
 85         @RenderBody()
 86 
 87         <hr />
 88 
 89         <footer>
 90 
 91             <p>&copy; 2017 - MvcMovie</p>
 92 
 93         </footer>
 94 
 95     </div>
 96 
 97  
 98 
 99     <environment names="Development">
100 
101         <script src="~/lib/jquery/dist/jquery.js"></script>
102 
103         <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
104 
105         <script src="~/js/site.js" asp-append-version="true"></script>
106 
107     </environment>
108 
109     <environment names="Staging,Production">
110 
111         <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
112 
113                 asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
114 
115                 asp-fallback-test="window.jQuery"
116 
117                 crossorigin="anonymous"
118 
119                 integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
120 
121         </script>
122 
123         <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
124 
125                 asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
126 
127                 asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
128 
129                 crossorigin="anonymous"
130 
131                 integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
132 
133         </script>
134 
135         <script src="~/js/site.min.js" asp-append-version="true"></script>
136 
137     </environment>
138 
139  
140 
141     @RenderSection("Scripts", required: false)
142 
143 </body>
144 
145 </html>

HTML code

Warning

注意

We haven’t implemented the Movies controller yet, so if you click on
that link, you’ll get a 404 (Not found) error.

因为我们还尚未落实 Movies
控制器,所以当你点击链接时,将会获取一个404谬误提醒。

Save your changes and tap the About link.

保留修改并点击 About
链接。

Notice how the title on the browser tab now displays About – Movie
App
 instead of About – Mvc Movie.

注意现行浏览器上标题显示已经由
About – Mvc Movie 变为 About – Movie App

Tap the Contact link and notice that it also displays Movie App.

点击 Contact
链接,注意看,现在呈现的也是 Movie App

We were able to make the change once in the layout template and have all
pages on the site reflect the new link text and new title.

大家得以在布局模板上做三回修改,然后让新的链接文本与标题突显到具有页面上。

Examine the Views/_ViewStart.cshtml file:

查看
Views/_ViewStart.cshtml  文件,如下:

图片 10图片 11

1 @{
2 
3     Layout = "_Layout";
4 
5 }

C# code

The Views/_ViewStart.cshtml file brings in
the Views/Shared/_Layout.cshtml file to each view.

Views/_ViewStart.cshtml 
文件将 Views/Shared/_Layout.cshtml 
文件中的布局设置带给了每一个视图页面。

You can use the Layout property to set a different layout view, or set
it to null so no layout file will be used.

你可以设置 Layout
属性,指定一个例外的布局视图,也足以赋值null代表没有此外布局被采纳。

Change the title of the Index view.

修改 Index 视图的题目。

Open Views/HelloWorld/Index.cshtml. There are two places to make a
change:

打开
Views/HelloWorld/Index.cshtml 文件,这有六个地方需要修改:

  • The text that appears in the title of the browser.

一个是浏览器上要来得的题目

  • The secondary header (<h2> element).

一个是<h2>标签里要出示的。

You’ll make them slightly different so you can see which bit of code
changes which part of the app.

您将会看到轻微的出入,这一点的代码与app的别样一些点。

图片 12图片 13

 1 @{
 2 
 3     ViewData["Title"] = "Movie List";
 4 
 5 }
 6 
 7  
 8 
 9 <h2>My Movie List</h2>
10 
11  
12 
13 <p>Hello from our View Template!</p>

HTML code

ViewData[“Title”] = “Movie List”; in the code above sets
the Title property of the ViewDatadictionary to “Movie List”.

在地点的代码中,给 ViewData
中的 Title 属性赋予 “Movie List” 这么些值。

The Title property is used in the <title> HTML element in the
layout page:

Title 这么些特性的值被布局页的
<title> 标签所使用,如下:

图片 14图片 15

1 <title>@ViewData["Title"] - Movie App</title>

HTML code

Save your change and navigate
to http://localhost:xxxx/HelloWorld.

保留修改,并导航至地方 http://localhost:xxxx/HelloWorld

Notice that the browser title, the primary heading, and the secondary
headings have changed.

瞩目浏览器的标题,第一级的标题,还有第二级的题目都已改成了。

(If you don’t see changes in the browser, you might be viewing cached
content.

如果您在浏览器中绝非看出变化,预计是你的页面内容被缓存了。

Press Ctrl+F5 in your browser to force the response from the server to
be loaded.)

按 Ctrl+F5
强制浏览器重新从服务器加载。

The browser title is created with ViewData[“Title”] we set in
the Index.cshtml view template and the additional “- Movie App” added
in the layout file.

浏览器的题目由 Index.cshtml 
中安装的 ViewData[“Title”] 值和布局页中的 “- Movie App”
 一起组成。

Also notice how the content in the Index.cshtml view template was
merged with the Views/Shared/_Layout.cshtml view template and a
single HTML response was sent to the browser.

一致需要注意的是,Index.cshtml 
视图与 Views/Shared/_Layout.cshtml
视图是何等统一在共同并发生一个HTML响应给浏览器的。

Layout templates make it really easy to make changes that apply across
all of the pages in your application.

布局模板万分便利的可以将转移反应到站点的兼具页面上。

To learn more
see Layout.

查看 Layout
可以赢得更多相关音讯。

 图片 16

Our little bit of “data” (in this case the “Hello from our View
Template!” message) is hard-coded, though.

尽管,我们的数量是硬编码在视图中的,

The MVC application has a “V” (view) and you’ve got a “C” (controller),
but no “M” (model) yet.

只是你曾经知晓了mvc应用的V和C,只剩下M了。

Passing Data from the Controller to the View

从控制器向视图传递数据

Controller actions are invoked in response to an incoming URL request.

控制器的action方法会被调用当有URL请求进入的时候。

A controller class is where you write the code that handles the incoming
browser requests.

控制器就是一个你用了写代码和拍卖浏览器请求的类。

The controller retrieves data from a data source and decides what type
of response to send back to the browser.

控制器可以从一个数据源获取数据并决定这种数据响应给浏览器。

View templates can be used from a controller to generate and format an
HTML response to the browser.

视图模板被操纵器用来扭转并格式化一个HTML响应重回给浏览器。

Controllers are responsible for providing the data required in order for
a view template to render a response.

控制器负责提供视图模板用来呈现响应所不可不的多少。

A best practice: View templates should not perform business logic or
interact with a database directly.

一个好的实践:视图不用直接跟数据库上拍卖工作逻辑与互相。

Rather, a view template should work only with the data that’s provided
to it by the controller.

本来,一个视图模板只需要运用控制器提供给他的数额表现界面就行了。

Maintaining this “separation of concerns” helps keep your code clean,
testable, and maintainable.

保障这种“关注点分离”可以使你的代码整洁、可测试与可保障。

Currently, the Welcome method in the HelloWorldController class takes
a name and a IDparameter and then outputs the values directly to the
browser.

时下,HelloWorldController
控制器中的 Welcome 方法拿到 name 、ID
三个参数并且直接出口一个值响应给浏览器。

Rather than have the controller render this response as a string, let’s
change the controller to use a view template instead.

无须这么一贯利用控制器重回一个字符串,让我们修改决定器用视图模板来代替做这些工作。

The view template will generate a dynamic response,

视图模板将会发出一个动态响应,

which means that you need to pass appropriate bits of data from the
controller to the view in order to generate the response.

这意味着你需要从控制器传递一些数码给视图,以便视图可以生成一个响应给浏览器。

You can do this by having the controller put the dynamic data
(parameters) that the view template needs in a ViewDatadictionary that
the view template can then access.

您可以在 ViewData
字典中动态的放入一些数量,然后视图模板就足以访问并行使这个数据。

Return to the HelloWorldController.cs file and change
the Welcome method to add a Message and NumTimes value to
the ViewData dictionary.

回到 HelloWorldController.cs
文件,修改 Welcome 方法,在 ViewData 字典中参预 Message 和 Num提姆es
的值。

The ViewData dictionary is a dynamic object, which means you can put
whatever you want in to it;

ViewData
字典是一个动态类型对象,你可以在里边放入任何你想放入的类型;

the ViewData object has no defined properties until you put something
inside it.

ViewData
对象在您放入数据前,里面没有其它性质与数量。

The MVC model binding
system
 automatically
maps the named parameters (name and numTimes) from the query string in
the address bar to parameters in your method.

Mvc 模型绑定系统
会自动将url中的命名参数的值映射赋值到您的action方法上。

The complete HelloWorldController.cs file looks like this:

HelloWorldController.cs
最后的代码如下所示:

图片 17图片 18

 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 : Controller
12 
13     {
14 
15         public IActionResult Index()
16 
17         {
18 
19             return View();
20 
21         }
22 
23  
24 
25         public IActionResult Welcome(string name, int numTimes = 1)
26 
27         {
28 
29             ViewData["Message"] = "Hello " + name;
30 
31             ViewData["NumTimes"] = numTimes;
32 
33  
34 
35             return View();
36 
37         }
38 
39     }
40 
41 }

C# code

The ViewData dictionary object contains data that will be passed to the
view.

ViewData
字典包含了要传送给视图的数目。

Create a Welcome view template named Views/HelloWorld/Welcome.cshtml.

创制视图模板文件并取名为
Views/HelloWorld/Welcome.cshtml

You’ll create a loop in the Welcome.cshtml view template that displays
“Hello” NumTimes.

你将创建一个巡回在
Welcome.cshtml  视图中,显示 NumTimes 次 “Hello” 。

Replace the contents of Views/HelloWorld/Welcome.cshtml with the
following:

用下边的代码 替换
Views/HelloWorld/Welcome.cshtml 中的内容:

图片 19图片 20

 1 @{
 2 
 3     ViewData["Title"] = "Welcome";
 4 
 5 }
 6 
 7  
 8 
 9 <h2>Welcome</h2>
10 
11  
12 
13 <ul>
14 
15     @for (int i = 0; i < (int)ViewData["NumTimes"]; i++)
16 
17     {
18 
19         <li>@ViewData["Message"]</li>
20 
21     }
22 
23 </ul>

HTML code

Save your changes and browse to the following URL:

保留修改并在浏览器中访问下边的地点:

http://localhost:xxxx/HelloWorld/Welcome?name=Rick&numtimes=4

Data is taken from the URL and passed to the controller using the MVC
model
binder
 .

参数数据由URL通过MVC模型绑定传递给控制器。

The controller packages the data into a ViewData dictionary and passes
that object to the view.

控制器通过 ViewData
字典对象包裹数据并传递给视图。

The view then renders the data as HTML to the browser.

下一场视图将数据渲染为HTML发送给浏览器。

 图片 21

In the sample above, we used the ViewData dictionary to pass data from
the controller to a view.

在上边的事例中,我们应用
ViewData 字典将数据从控制器传递给视图。

Later in the tutorial, we will use a view model to pass data from a
controller to a view.

在稍后的学科中,大家会采用一个
vm (视图模型 view model)将数据从控制器传递给视图。

The view model approach to passing data is generally much preferred over
the ViewData dictionary approach.

视图模型通过 ViewData
字典传递数据,

See ViewModel vs ViewData vs ViewBag vs TempData vs Session in
MVC
 for
more information.

查看 ViewModel vs ViewData vs ViewBag vs
TempData vs Session in
MVC

以博取更多音信。

Well, that was a kind of an “M” for model, but not the database kind.
Let’s take what we’ve learned and create a database of movies.

好了,这是M的一种,但不是数据库这种
model,让自家用学到的始建一个DB 电影库。(看下一节)

 

 

 

                                         蒙

                                    2017-07-14
17:06 周五

 

相关文章