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

索引:css

目录索引html

Adding a view to an ASP.NET Core MVC appjquery

在asp.net core mvc中添加视图ajax

2017-3-4 7 分钟阅读时长 数据库

本文内容bootstrap

1.Changing views and layout pagesapi

修改视图和布局页浏览器

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 " + 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 中的内容:

 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发送给浏览器。

 

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 周五

相关文章
相关标签/搜索