010.Controller methods and views --【控制器方法與視圖】

来源:http://www.cnblogs.com/Meng-NET/archive/2017/08/16/7374941.html
-Advertisement-
Play Games

Controller methods and views 控制器方法與視圖 2017-3-7 9 分鐘閱讀時長 作者 By Rick Anderson We have a good start to the movie app, but the presentation is not ideal. ...


Controller methods and views

控制器方法與視圖

2017-3-7 9 分鐘閱讀時長 作者 

By Rick Anderson

We have a good start to the movie app, but the presentation is not ideal.

我們在movie 應用上已經有了一個好的開始,但是表現層不是很理想。

We don't want to see the time (12:00:00 AM in the image below) and ReleaseDateshould be two words.

我們不想看到下圖中顯示的(12:00:00 AM)並且 ReleaseDate 欄位應該顯示為兩個單詞。

 

Open the Models/Movie.cs file and add the highlighted lines shown below:

打開 Models/Movie.cs 文件並且添加下麵高亮行的代碼:

 1 using System;
 2 
 3 using System.Collections.Generic;
 4 
 5 using System.Linq;
 6 
 7 using System.Threading.Tasks;
 8 
 9  
10 
11 namespace MvcMovie.Models
12 
13 {
14 
15     public class Movie
16 
17     {
18 
19         public int ID { get; set; }
20 
21         public string Title { get; set; }
22 
23  
24 
25         [Display(Name = "Release Date")]
26 
27         [DataType(DataType.Date)]
28 
29         public DateTime ReleaseDate { get; set; }
30 
31         public string Genre { get; set; }
32 
33         public decimal Price { get; set; }
34 
35     }
36 
37 }
C# code

Right click on a red squiggly line > Quick Actions and Refactorings.

在紅波浪線上右擊,選擇 Quick Actions and Refactorings.

Tap using System.ComponentModel.DataAnnotations;

點擊 using System.ComponentModel.DataAnnotations

 

Visual studio adds using System.ComponentModel.DataAnnotations;.

VS將自動添加 using System.ComponentModel.DataAnnotations 。

Let's remove the using statements that are not needed.

讓移除不需要的 using 語句 。

They show up by default in a light grey font. Right click anywhere in the Movie.cs file > Remove and Sort Usings.

他們預設以灰色字體顯示。右擊 Movie.cs 文件的任何地方,選擇 Remove and Sort Usings

 

The updated code:

更新後的代碼如下:

 1 using System;
 2 
 3 using System.ComponentModel.DataAnnotations;
 4 
 5  
 6 
 7 namespace MvcMovie.Models
 8 
 9 {
10 
11     public class Movie
12 
13     {
14 
15         public int ID { get; set; }
16 
17         public string Title { get; set; }
18 
19  
20 
21         [Display(Name = "Release Date")]
22 
23         [DataType(DataType.Date)]
24 
25         public DateTime ReleaseDate { get; set; }
26 
27         public string Genre { get; set; }
28 
29         public decimal Price { get; set; }
30 
31     }
32 
33 }
C# code

We'll cover DataAnnotations in the next tutorial.

我們將在接下來的教程中講解數據註解特性。

The Display attribute specifies what to display for the name of a field (in this case "Release Date" instead of "ReleaseDate").

Display 特性特別的指定了該欄位在界面顯示時所要顯示的名字(用 Release Date 代替了 ReleaseDate)。

The DataType attribute specifies the type of the data (Date), so the time information stored in the field is not displayed.

DataType 特性特別指定了數據的顯示類型(日期),因此欄位裡面存儲的時間信息就不再顯示了。

Browse to the Movies controller and hold the mouse pointer over an Edit link to see the target URL.

導航到 Movies 地址,在頁面上將滑鼠放到 Edit 鏈接上,並查看目標URL.

 

The EditDetails, and Delete links are generated by the MVC Core Anchor Tag Helper in the Views/Movies/Index.cshtml file.

Views/Movies/Index.cshtml  文件中的 EditDetails和 Delete 鏈接由mvc鏈接幫助類自動生成的。

1         <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
2 
3         <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
4 
5         <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
6 
7     </td>
8 
9 </tr>
HTML Code

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files.

Tag Helpers 是在服務端參與產生與渲染HTML的。

In the code above,

在上面的代碼中,

the AnchorTagHelperdynamically generates the HTML href attribute value from the controller action method and route id.

AnchorTagHelper 動態的生成了html中的href 特征屬性的值 (控制器方法與方法的id參數)。

You use View Source from your favorite browser or use the developer tools to examine the generated markup.

你可以使用瀏覽器的 View Source 或開發工具查看 自動生成的 html 標記。

A portion of the generated HTML is shown below:

部分html如下所示:

1  <td>
2 
3     <a href = "/Movies/Edit/4" > Edit </ a > |
4 
5     < a href="/Movies/Details/4">Details</a> |
6 
7     <a href = "/Movies/Delete/4" > Delete </ a >
8 
9 </ td >
HTML Code

Recall the format for routing set in the Startup.cs file:

回想 Startup.cs 文件中的路由設置,如下:

 1 app.UseMvc(routes =>
 2 
 3 {
 4 
 5     routes.MapRoute(
 6 
 7         name: "default",
 8 
 9         template: "{controller=Home}/{action=Index}/{id?}");
10 
11 });
C# code

ASP.NET Core translates http://localhost:1234/Movies/Edit/4 into a request to the Edit action method of the Movies controller with the parameter Id of 4. (Controller methods are also known as action methods.)

Asp.net core 翻譯 http://localhost:1234/Movies/Edit/4 地址為對 Movies 控制器中方法Edit 的請求,並且參數為4.

Tag Helpers are one of the most popular new features in ASP.NET Core.

Tag Helpers 是asp.net core 中最受歡迎的特點之一。

See Additional resources for more information.

查看 Additional resources 瞭解更多信息。

Open the Movies controller and examine the two Edit action methods.

打開 Movies  控制器,查看兩個 Edit  方法的代碼。

The following code shows the HTTP GET Edit method, which fetches the movie and populates the edit form generated by the Edit.cshtml Razor file.

下麵的代碼是 HTTP GET Edit 方法,他讀取了movie數據並填充了由 Edit.cshtml 文件生成的編輯表單。

 1 // GET: Movies/Edit/5
 2 
 3 public async Task<IActionResult> Edit(int? id)
 4 
 5 {
 6 
 7     if (id == null)
 8 
 9     {
10 
11         return NotFound();
12 
13     }
14 
15  
16 
17     var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
18 
19     if (movie == null)
20 
21     {
22 
23         return NotFound();
24 
25     }
26 
27     return View(movie);
28 
29 }
C# code

The following code shows the HTTP POST Edit method, which processes the posted movie values:

下麵的代碼展示了 HTTP POST Edit 方法,他處理了post請求過來的movie數據:

 1 // POST: Movies/Edit/5
 2 
 3 // To protect from overposting attacks, please enable the specific properties you want to bind to, for
 4 
 5 // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
 6 
 7 [HttpPost]
 8 
 9 [ValidateAntiForgeryToken]
10 
11 public async Task<IActionResult> Edit(int id, [Bind("ID,Title,ReleaseDate,Genre,Price")] Movie movie)
12 
13 {
14 
15     if (id != movie.ID)
16 
17     {
18 
19         return NotFound();
20 
21     }
22 
23  
24 
25     if (ModelState.IsValid)
26 
27     {
28 
29         try
30 
31         {
32 
33             _context.Update(movie);
34 
35             await _context.SaveChangesAsync();
36 
37         }
38 
39         catch (DbUpdateConcurrencyException)
40 
41         {
42 
43             if (!MovieExists(movie.ID))
44 
45             {
46 
47                 return NotFound();
48 
49             }
50 
51             else
52 
53             {
54 
55                 throw;
56 
57             }
58 
59         }
60 
61         return RedirectToAction("Index");
62 
63     }
64 
65     return View(movie);
66 
67 }
C# code

The [Bind] attribute is one way to protect against over-posting.

[Bind] 特性標記是一種post攻擊防護方式。

You should only include properties in the [Bind] attribute that you want to change.

你應當只做 [Bind] 特征類中包含的欄位的變更。

See Protect your controller from over-posting for more information. 

查看 Protect your controller from over-posting 以獲得更多信息。

ViewModels provide an alternative approach to prevent over-posting.

ViewModels 提供一種預防 over-posting 攻擊的方式。

Notice the second Edit action method is preceded by the [HttpPost] attribute.

註意第二個 Edit 方法被 [HttpPost] 特征類修飾。

 1 // POST: Movies/Edit/5
 2 
 3 // To protect from overposting attacks, please enable the specific properties you want to bind to, for
 4 
 5 // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
 6 
 7 [HttpPost]
 8 
 9 [ValidateAntiForgeryToken]
10 
11 public async Task<IActionResult> Edit(int id, [Bind("ID,Title,ReleaseDate,Genre,Price")] Movie movie)
12 
13 {
14 
15     if (id != movie.ID)
16 
17     {
18 
19         return NotFound();
20 
21     }
22 
23  
24 
25     if (ModelState.IsValid)
26 
27     {
28 
29         try
30 
31         {
32 
33             _context.Update(movie);
34 
35             await _context.SaveChangesAsync();
36 
37         }
38 
39         catch (DbUpdateConcurrencyException)
40 
41         {
42 
43             if (!MovieExists(movie.ID))
44 
45             {
46 
47                 return NotFound();
48 
49             }
50 
51             else
52 
53             {
54 
55                 throw;
56 
57             }
58 
59         }
60 
61         return RedirectToAction("Index");
62 
63     }
64 
65     return View(movie);
66 
67 }
C# code

The HttpPost attribute specifies that this Edit method can be invoked only for POST requests.

HttpPost 標記特別指定了 Edit 方法只能被 POST 請求調用。

You could apply the [HttpGet] attribute to the first edit method, but that's not necessary because [HttpGet] is the default.

你可以在第一個 edit 方法上使用 [HttpGet] 特征類,單他不是必須的,因為方法預設是 [HttpGet] 請求的。

The ValidateAntiForgeryToken attribute is used to prevent forgery of a requestand is paired up with an anti-forgery token generated in the edit view file (Views/Movies/Edit.cshtml).

ValidateAntiForgeryToken 標記類使用了預防偽造請求,並與 edit 視圖生成的反偽造令牌是配對的。

The edit view file generates the anti-forgery token with the Form Tag Helper.

edit 視圖生成的anti-forgery 令牌是通過 Form Tag Helper 生成的。

1 <form asp-action="Edit">
HTML Code

The Form Tag Helper generates a hidden anti-forgery token that must match the [ValidateAntiForgeryToken] generated anti-forgery token in the Edit method of the Movies controller.

Form Tag Helper 生成了一個隱藏域的令牌欄位,並且他是匹配Movies控制器中Edit 方法上的[ValidateAntiForgeryToken] 標記生成的令牌的。

For more information, see Anti-Request Forgery.

查看  Anti-Request Forgery ,以獲得更多信息。

The HttpGet Edit method takes the movie ID parameter, looks up the movie using the Entity Framework SingleOrDefaultAsync method, and returns the selected movie to the Edit view.

HttpGet Edit 方法獲取 ID 參數,查看 EF 的 SingleOrDefaultAsync 方法,它會查找並將movie數據返回給 Edit 視圖。

If a movie cannot be found, NotFound (HTTP 404) is returned.

如果movie數據沒有找到,將返回 NotFound 。

 1 // GET: Movies/Edit/5
 2 
 3 public async Task<IActionResult> Edit(int? id)
 4 
 5 {
 6 
 7     if (id == null)
 8 
 9     {
10 
11         return NotFound();
12 
13     }
14 
15  
16 
17     var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
18 
19     if (movie == null)
20 
21     {
22 
23         return NotFound();
24 
25     }
26 
27     return View(movie);
28 
29 }
C# code

When the scaffolding system created the Edit view, it examined the Movie class and created code to render <label> and <input> elements for each property of the class.

當MVC基架系統創建了 Edit 視圖,它會自動檢查 Movie 類的每個屬性,並未每個屬性創建HTML元素。

The following example shows the Edit view that was generated by the Visual Studio scaffolding system:

下麵的例子展示了VS基架系統自動生成的 Edit 視圖:

  1 @model MvcMovie.Models.Movie
  2 
  3  
  4 
  5 @{
  6 
  7     ViewData["Title"] = "Edit";
  8 
  9 }
 10 
 11  
 12 
 13 <h2>Edit</h2>
 14 
 15  
 16 
 17 <form asp-action="Edit">
 18 
 19     <div class="form-horizontal">
 20 
 21         <h4>Movie</h4>
 22 
 23         <hr />
 24 
 25         <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 26 
 27     <input type="hidden" asp-for="ID" />
 28 
 29         <div class="form-group">
 30 
 31             <label asp-for="Title" class="col-md-2 control-label"></label>
 32 
 33             <div class="col-md-10">
 34 
 35                 <input asp-for="Title" class="form-control" />
 36 
 37                 <span asp-validation-for="Title" class="text-danger"></span>
 38 
 39             </div>
 40 
 41         </div>
 42 
 43         <div class="form-group">
 44 
 45             <label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
 46 
 47             <div class="col-md-10">
 48 
 49                 <input asp-for="ReleaseDate" class="form-control" />
 50 
 51                 <span asp-validation-for="ReleaseDate" class="text-danger"></span>
 52 
 53             </div>
 54 
 55         </div>
 56 
 57         <div class="form-group">
 58 
 59             <label asp-for="Genre" class="col-md-2 control-label"></label>
 60 
 61             <div class="col-md-10">
 62 
 63                 <input asp-for="Genre" class="form-control" />
 64 
 65                 <span asp-validation-for="Genre" class="text-danger"></span>
 66 
 67             </div>
 68 
 69         </div>
 70 
 71         <div class="form-group">
 72 
 73             <label asp-for="Price" class="col-md-2 control-label"></label>
 74 
 75             <div class="col-md-10">
 76 
 77                 <input asp-for="Price" class="form-control" />
 78 
 79                 <span asp-validation-for="Price" class="text-danger"></span>
 80 
 81             </div>
 82 
 83         </div>
 84 
 85         <div class="form-group">
 86 
 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • CREATE DEFINER=`sas_settle`@`%` PROCEDURE `P_CREATE_ACCOUNT_CARRIER_TASK`() BEGIN DECLARE done INT DEFAULT 0; DECLARE v_flow_id VARCHAR(10); -- 流水號 DE... ...
  • VMware tools是虛擬機上虛擬硬體的驅動,可以實現滑鼠的無縫移出移入,剪貼板共用,共用文件夾等功能。很多的Linux系統初學者,在安裝centos6.9系統時,沒有安裝VMware tools,但是想要安裝VMware tools要使用命令行方式。這對於Linux初學者來說有一定的困難,本文 ...
  • 一、概述 vi中基本的游標移動命令有:h、j、k、l。 其中,h為游標左移1位,j為游標下移1行,k為游標上移1行,l為游標右移1位。 上述命令支持“數字+命令”格式,1次移動多位(行)。 二、示例 初始狀態 01234 0123 012 運行命令:l 01234 0123 012 運行命令:3l ...
  • 我們在本地部署了自己的nuget伺服器,有時可以需要用到nuget restore命令去恢復包包,它會從下麵的nuget.config里讀你的配置源信息,就是在這裡,我們要把內測的nuget伺服器路徑添加上,這樣就可以了。 NUGET服務配置地址:%AppData%\Nuget\ 關鍵信息 有興趣的 ...
  • 在centos上搭建一個ftp,一切都配置好之後,我去訪問時仍然會出現425 Failed to establish connection.這個錯誤,經過一番查找,原來是這個 -A INPUT -j REJECT --reject-with icmp-host-prohibited -A FORWA ...
  • 有了前兩講的基礎,這回我們就可以把github上的項目做到CI(jenkins)里了,讓它自動去集成部署,持續集成~Jenkins里的NuGet和MSBuild插件,持續集成~Jenkins里的powershell插件發佈遠程站點了,下麵我們來說一下操作步驟。 進行jenkins操作 http:// ...
  • 一、proc文件系統是什麼? proc是一個偽文件系統,偽文件系統的定義: 它只存在記憶體當中,而不占用外存空間。它以文件系統的方式為訪問系統內核數據的操作提供介面。用戶和應用程式可以通過proc得到系統的信息,並可以改變內核的某些參數。由於系統的信息,如進程,是動態改變的,所以用戶或應用程式讀取pr ...
  • .NET Core 2.0發佈日期:2017年8月14日 前言 這一篇會比較長,介紹了.NET Core 2.0新特性、工具支持及系統生態,現狀及未來計劃,可以作為一門技術的概述來讀,也可以作為學習路徑、提綱來用。 對於.NET Core 2.0的發佈介紹,圍繞2.0的架構體系,我想通過一個系列來全 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...