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 a ...
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
從控制器向視圖傳遞數據
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 Home, About, and Contact links.
你可能需要點擊右上角的導航菜單才能看到 Home, About, Contact 鏈接。
Changing views and layout pages
修改視圖與佈局頁
Tap the menu links (MvcMovie, Home, About). 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>© 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 字典將數據從控制器傳遞給視圖。