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

Posted Meng.NET

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 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

 

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

使用下面的代码替换 Views/HelloWorld/Index.cshtml  文件中的代码:

 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!” 。

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  链接。

 

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:

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

  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                     <span class="sr-only">Toggle navigation</span>
 52 
 53                     <span class="icon-bar"></span>
 54 
 55                     <span class="icon-bar"></span>
 56 
 57                     <span class="icon-bar"></span>
 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  文件,如下:

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的其它部分点。

 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> 标签所使用,如下:

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 可以获得更多相关信息。

 

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 和 NumTimes 的值。

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 最终的代码如下所示:

 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 以上是关于007.Adding a view to an ASP.NET Core MVC app -- 在asp.net core mvc中添加视图的主要内容,如果未能解决你的问题,请参考以下文章

[TS] Parse a string to an integer

Adding a prefix header to an iOS project

Arrange an Array to Form a Smallest Digit

iOS项目添加.pch文件 / How to add a .pch file to an iOS project

Java——Read/convert an InputStream to a String

关于An association from the table refers to an unmapped class