在本節中,您將開始修改為電影控制器所新加的操作方法和視圖。然后,您將添加一個自定義的搜索頁。
在瀏覽器地址欄里追加/Movies, 瀏覽到Movies頁面。並進入編輯(Edit)頁面。
Edit(編輯)鏈接是由Views\Movies\Index.cshtml視圖中的Html.ActionLink
方法所生成的:
@Html.ActionLink("Edit", "Edit", new { id=item.ID })
Html
對象是一個Helper, 以屬性的形式, 在System.Web.Mvc.WebViewPage基類上公開。 ActionLink是一個幫助方法,便於動態生成指向Controller中操作方法的HTML 超鏈接鏈接。ActionLink
方法的第一個參數是想要呈現的鏈接文本 (例如,<a>Edit Me</a>
)。第二個參數是要調用的操作方法的名稱。最后一個參數是一個匿名對象,用來生成路由數據 (在本例中,ID 為 4 的)。
在上圖中所生成的鏈接是http://localhost:xxxxx/Movies/Edit/4默認的路由 (在App_Start\RouteConfig.cs 中設定) 使用的 URL 匹配模式為: {controller}/{action}/{id}
。因此,ASP.NET 將http://localhost:xxxxx/Movies/Edit/4轉化到Movies
控制器中Edit
操作方法,參數ID
等於 4 的請求。查看App_Start\RouteConfig.cs文件中的以下代碼。
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
您還可以使用QueryString來傳遞操作方法的參數。例如,URL: http://localhost:xxxxx/Movies/Edit?ID=4還會將參數ID
為 4的請求傳遞給Movies
控制器的Edit
操作方法。
打開Movies
控制器。如下所示的兩個Edit
操作方法。
// // GET: /Movies/Edit/5 public ActionResult Edit(int id = 0) { Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // // POST: /Movies/Edit/5 [HttpPost] public ActionResult Edit(Movie movie) { if (ModelState.IsValid) { db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); }
注意,第二個Edit
操作方法的上面有HttpPost屬性。此屬性指定了Edit
方法的重載,此方法僅被POST 請求所調用。您可以將HttpGet屬性應用於第一個編輯方法,但這是不必要的,因為它是默認的屬性。(操作方法會被隱式的指定為HttpGet
屬性,從而作為HttpGet
方法。)
HttpGet
Edit
方法會獲取電影ID參數、 查找影片使用Entity Framework 的Find
方法,並返回到選定影片的編輯視圖。如果不帶參數調用Edit
方法,ID 參數被指定為默認值 零。如果找不到一部電影,則返回HttpNotFound 。當VS自動創建編輯視圖時,它會查看Movie
類並為類的每個屬性創建用於Render的<label>
和<input>
的元素。下面的示例為自動創建的編輯視圖:
@model MvcMovie.Models.Movie @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Movie</legend> @Html.HiddenFor(model => model.ID) <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.ReleaseDate) </div> <div class="editor-field"> @Html.EditorFor(model => model.ReleaseDate) @Html.ValidationMessageFor(model => model.ReleaseDate) </div> <div class="editor-label"> @Html.LabelFor(model => model.Genre) </div> <div class="editor-field"> @Html.EditorFor(model => model.Genre) @Html.ValidationMessageFor(model => model.Genre) </div> <div class="editor-label"> @Html.LabelFor(model => model.Price) </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
注意,視圖模板在文件的頂部有 @model MvcMovie.Models.Movie
的聲明,這將指定視圖期望的模型類型為Movie
。
自動生成的代碼,使用了Helper方法的幾種簡化的 HTML 標記。 Html.LabelFor
用來顯示字段的名稱("Title"、"ReleaseDate"、"Genre"或"Price")。 Html.EditorFor
用來呈現 HTML <input>
元素。Html.ValidationMessageFor
用來顯示與該屬性相關聯的任何驗證消息。
運行該應用程序,然后瀏覽URL,/Movies。單擊Edit鏈接。在瀏覽器中查看頁面源代碼。HTML Form中的元素如下所示:
<form action="/Movies/Edit/4" method="post"> <fieldset> <legend>Movie</legend> <input data-val="true" data-val-number="The field ID must be a number." data-val-required="The ID field is required." id="ID" name="ID" type="hidden" value="4" /> <div class="editor-label"> <label for="Title">Title</label> </div> <div class="editor-field"> <input class="text-box single-line" id="Title" name="Title" type="text" value="Rio Bravo" /> <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span> </div> <div class="editor-label"> <label for="ReleaseDate">ReleaseDate</label> </div> <div class="editor-field"> <input class="text-box single-line" data-val="true" data-val-date="The field ReleaseDate must be a date." data-val-required="The ReleaseDate field is required." id="ReleaseDate" name="ReleaseDate" type="text" value="4/15/1959 12:00:00 AM" /> <span class="field-validation-valid" data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span> </div> <div class="editor-label"> <label for="Genre">Genre</label> </div> <div class="editor-field"> <input class="text-box single-line" id="Genre" name="Genre" type="text" value="Western" /> <span class="field-validation-valid" data-valmsg-for="Genre" data-valmsg-replace="true"></span> </div> <div class="editor-label"> <label for="Price">Price</label> </div> <div class="editor-field"> <input class="text-box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-required="The Price field is required." id="Price" name="Price" type="text" value="2.99" /> <span class="field-validation-valid" data-valmsg-for="Price" data-valmsg-replace="true"></span> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> </form>
被<form>
HTML 元素所包括的 <input>
元素會被發送到,form的action
屬性所設置的URL:/Movies/Edit。單擊Edit按鈕時,from數據將會被發送到服務器。
處理 POST 請求
下面的代碼顯示了Edit
操作方法的HttpPost
處理:
[HttpPost] public ActionResult Edit(Movie movie) { if (ModelState.IsValid) { db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); }
ASP.NET MVC 模型綁定 接收form所post的數據,並轉換所接收的movie
請求數據從而創建一個Movie
對象。ModelState.IsValid
方法用於驗證提交的表單數據是否可用於修改(編輯或更新)一個Movie
對象。如果數據是有效的電影數據,將保存到數據庫的Movies
集合(MovieDBContext
instance)。通過調用MovieDBContext
的SaveChanges
方法,新的電影數據會被保存到數據庫。數據保存之后,代碼會把用戶重定向到MoviesController
類的Index
操作方法,頁面將顯示電影列表,同時包括剛剛所做的更新。
如果form發送的值不是有效的值,它們將重新顯示在form中。Edit.cshtml視圖模板中的Html.ValidationMessageFor
Helper將用來顯示相應的錯誤消息。
注意,為了使jQuery支持使用逗號的非英語區域的驗證 ,需要設置逗號(",")來表示小數點,你需要引入globalize.js並且你還需要具體的指定cultures/globalize.cultures.js文件 (地址在https://github.com/jquery/globalize) 在 JavaScript 中可以使用 Globalize.parseFloat
。下面的代碼展示了在"FR-FR" Culture下的 Views\Movies\Edit.cshtml 視圖:
@section Scripts { @Scripts.Render("~/bundles/jqueryval") <script src="~/Scripts/globalize.js"></script> <script src="~/Scripts/globalize.culture.fr-FR.js"></script> <script> $.validator.methods.number = function (value, element) { return this.optional(element) || !isNaN(Globalize.parseFloat(value)); } $(document).ready(function () { Globalize.culture('fr-FR'); }); </script> <script> jQuery.extend(jQuery.validator.methods, { range: function (value, element, param) { //Use the Globalization plugin to parse the value var val = $.global.parseFloat(value); return this.optional(element) || ( val >= param[0] && val <= param[1]); } }); </script> }
十進制字段可能需要逗號,而不是小數點。作為臨時的修復,您可以向項目根 web.config 文件添加的全球化設置。下面的代碼演示設置為美國英語的全球化文化設置。
<system.web>
<globalization culture ="en-US" />
<!--elements removed for clarity-->
</system.web>
所有HttpGet
方法都遵循類似的模式。它們獲取影片對象 (或對象集合,如Index
里的對象集合),並將模型傳遞給視圖。Create
方法將一個空的Movie對象傳遞給創建視圖。創建、 編輯、 刪除或以其它方式修改數據的方法都是HttpPost
方法。使用HTTP GET 方法來修改數據是存在安全風險,在ASP.NET MVC Tip #46 – Don’t use Delete Links because they create Security Holes的Blog中有完整的敘述。在 GET 方法中修改數據還違反了 HTTP 的最佳做法和Rest架構模式, GET 請求不應更改應用程序的狀態。換句話說,執行 GET 操作,應該是一種安全的操作,沒有任何副作用,不會修改您持久化的數據。
添加一個搜索方法和搜索視圖
在本節中,您將添加一個搜索電影流派或名稱的SearchIndex
操作方法。這將可使用/Movies/SearchIndex URL。該請求將顯示一個 HTML 表單,其中包含輸入的元素,用戶可以輸入一部要搜索的電影。當用戶提交窗體時,操作方法將獲取用戶輸入的搜索條件並在數據庫中搜索。
顯示 SearchIndex 窗體
通過將SearchIndex
操作方法添加到現有的MoviesController
類開始。該方法將返回一個視圖包含一個 HTML 表單。如下代碼:
public ActionResult SearchIndex(string searchString) { var movies = from m in db.Movies select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } return View(movies); }
SearchIndex
方法的第一行創建以下的LINQ查詢,以選擇看電影:
var movies = from m in db.Movies select m;
查詢在這一點上,只是定義,並還沒有執行到數據上。
如果searchString
參數包含一個字符串,可以使用下面的代碼,修改電影查詢要篩選的搜索字符串:
if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); }
上面s => s.Title
代碼是一個Lambda 表達式。Lambda 是基於方法的LINQ查詢,(例如上面的where查詢)在上面的代碼中使用了標准查詢參數運算符的方法。當定義LINQ查詢或修改查詢條件時(如調用Where
或OrderBy
方法時,不會執行 LINQ 查詢。相反,查詢執行會被延遲,這意味着表達式的計算延遲,直到取得實際的值或調用ToList
方法。在SearchIndex
示例中,SearchIndex 視圖中執行查詢。有關延遲的查詢執行的詳細信息,請參閱Query Execution.
現在,您可以實現SearchIndex
視圖並將其顯示給用戶。在SearchIndex
方法內單擊右鍵,然后單擊添加視圖。在添加視圖對話框中,指定你要將Movie
對象傳遞給視圖模板作為其模型類。在框架模板列表中,選擇列表,然后單擊添加.
當您單擊添加按鈕時,創建了Views\Movies\SearchIndex.cshtml視圖模板。因為你選中了框架模板的列表,Visual Studio 將自動生成列表視圖中的某些默認標記。框架模版創建了 HTML 表單。它會檢查Movie
類,並為類的每個屬性創建用來展示的<label>
元素。下面是生成的視圖:
@model IEnumerable<MvcMovie.Models.Movie> @{ ViewBag.Title = "SearchIndex"; } <h2>SearchIndex</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> Title </th> <th> ReleaseDate </th> <th> Genre </th> <th> Price </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Html.ActionLink("Delete", "Delete", new { id=item.ID }) </td> </tr> } </table>
運行該應用程序,然后轉到 /Movies/SearchIndex。追加查詢字符串到URL如?searchString=ghost
。顯示已篩選的電影。
如果您更改SearchIndex
方法的簽名,改為參數id
,在Global.asax文件中設置的默認路由將使得: id
參數將匹配{id}
占位符。
{controller}/{action}/{id}
原來的SearchIndex
方法看起來是這樣的:
public ActionResult SearchIndex(string searchString) { var movies = from m in db.Movies select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } return View(movies); }
修改后的SearchIndex
方法將如下所示:
public ActionResult SearchIndex(string id) { string searchString = id; var movies = from m in db.Movies select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } return View(movies); }
您現在可以將搜索標題作為路由數據 (部分URL) 來替代QueryString。
但是,每次用戶想要搜索一部電影時, 你不能指望用戶去修改 URL。所以,現在您將添加 UI頁面,以幫助他們去篩選電影。如果您更改了的SearchIndex
方法來測試如何傳遞路由綁定的 ID 參數,更改它,以便您的SearchIndex
方法采用字符串searchString
參數:
public ActionResult SearchIndex(string searchString) { var movies = from m in db.Movies select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } return View(movies); }
打開Views\Movies\SearchIndex.cshtml文件,並在 @Html.ActionLink("Create New", "Create")
后面,添加以下內容:
@using (Html.BeginForm()){ <p> Title: @Html.TextBox("SearchString")<br /> <input type="submit" value="Filter" /></p> }
下面的示例展示了添加后, Views\Movies\SearchIndex.cshtml 文件的一部分:
@model IEnumerable<MvcMovie.Models.Movie> @{ ViewBag.Title = "SearchIndex"; } <h2>SearchIndex</h2> <p> @Html.ActionLink("Create New", "Create") @using (Html.BeginForm()){ <p> Title: @Html.TextBox("SearchString") <br /> <input type="submit" value="Filter" /></p> } </p>
Html.BeginForm Helper
創建開放<form>
標記。Html.BeginForm
Helper將使得, 在用戶通過單擊篩選按鈕提交窗體時,窗體Post本Url。運行該應用程序,請嘗試搜索一部電影。
SearchIndex
沒有HttpPost
的重載方法。你並不需要它,因為該方法並不更改應用程序數據的狀態,只是篩選數據。
您可以添加如下的HttpPost SearchIndex
方法。在這種情況下,請求將進入HttpPost SearchIndex
方法,
HttpPost SearchIndex
方法將返回如下圖的內容。
[HttpPost] public string SearchIndex(FormCollection fc, string searchString) { return "<h3> From [HttpPost]SearchIndex: " + searchString + "</h3>"; }
但是,即使您添加此HttpPost
SearchIndex
方法,這一實現其實是有局限的。想象一下您想要添加書簽給特定的搜索,或者您想要把搜索鏈接發送給朋友們,他們可以通過單擊看到一樣的電影搜索列表。請注意 HTTP POST 請求的 URL 和GET 請求的URL 是相同的(localhost:xxxxx/電影/SearchIndex)— — 在 URL 中沒有搜索信息。現在,搜索字符串信息作為窗體字段值,發送到服務器。這意味着您不能在 URL 中捕獲此搜索信息,以添加書簽或發送給朋友。
解決方法是使用重載的BeginForm
,它指定 POST 請求應添加到 URL 的搜索信息,並應該路由到 HttpGet SearchIndex
方法。將現有的無參數BeginForm
方法,修改為以下內容:
@using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get))
現在當您提交搜索,該 URL 將包含搜索的查詢字符串。搜索還會請求到 HttpGet SearchIndex
操作方法,即使您也有一個HttpPost SearchIndex
方法。
按照電影流派添加搜索
如果您添加了HttpPost
的SearchIndex
方法,請立即刪除它。
接下來,您將添加功能可以讓用戶按流派搜索電影。將SearchIndex
方法替換成下面的代碼:
public ActionResult SearchIndex(string movieGenre, string searchString) { var GenreLst = new List<string>(); var GenreQry = from d in db.Movies orderby d.Genre select d.Genre; GenreLst.AddRange(GenreQry.Distinct()); ViewBag.movieGenre = new SelectList(GenreLst); var movies = from m in db.Movies select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } if (string.IsNullOrEmpty(movieGenre)) return View(movies); else { return View(movies.Where(x => x.Genre == movieGenre)); } }
這版的SearchIndex
方法將接受一個附加的movieGenre
參數。前幾行的代碼會創建一個List
對象來保存數據庫中的電影流派。
下面的代碼是從數據庫中檢索所有流派的 LINQ 查詢。
var GenreQry = from d in db.Movies orderby d.Genre select d.Genre;
該代碼使用泛型 List集合的 AddRange方法將所有不同的流派,添加到集合中的。(使用 Distinct
修飾符,不會添加重復的流派 -- 例如,在我們的示例中添加了兩次喜劇)。該代碼然后在ViewBag
對象中存儲了流派的數據列表。
下面的代碼演示如何檢查movieGenre
參數。如果它不是空的,代碼進一步指定了所查詢的電影流派。
if (string.IsNullOrEmpty(movieGenre)) return View(movies); else { return View(movies.Where(x => x.Genre == movieGenre)); }
在SearchIndex 視圖中添加選擇框支持按流派搜索
在TextBox
Helper之前添加 Html.DropDownList
Helper到Views\Movies\SearchIndex.cshtml文件中。添加完成后,如下面所示:
<p> @Html.ActionLink("Create New", "Create") @using (Html.BeginForm("SearchIndex","Movies",FormMethod.Get)){ <p>Genre: @Html.DropDownList("movieGenre", "All") Title: @Html.TextBox("SearchString") <input type="submit" value="Filter" /></p> } </p>
運行該應用程序並瀏覽 /Movies/SearchIndex。按流派、 按電影名,或者同時這兩者,來嘗試搜索。
在這一節中您修改了CRUD 操作方法和框架所生成的視圖。您創建了一個搜索操作方法和視圖,讓用戶可以搜索電影標題和流派。在下一節中,您將看到如何將屬性添加到Movie
模型,以及如何添加一個初始設定並自動創建一個測試數據庫。以上創建搜索方法和視圖的示例是為了幫助大家更好的掌握MVC的知識,在進行MVC開發時,開發工具也可以大大幫助提高工具效率。使用 ComponentOne Studio ASP.NET MVC 這款輕量級控件,在效率大幅提高的同時,還能滿足用戶的所有需求。
完整文檔下載:Asp.Net MVC4入門指南.pdf
--------------------------------------------------------------------------------------------------------------------
譯者注:
本系列共9篇文章,翻譯自Asp.Net MVC4 官方教程,由於本系列文章言簡意賅,篇幅適中,從一個示例開始講解,全文最終完成了一個管理影片的小系統,非常適合新手入門Asp.Net MVC4,並由此開始開發工作。9篇文章為:
1. Asp.Net MVC4 入門介紹
· 原文地址:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2012/11/01/2749906.html
2. 添加一個控制器
· 原文地址:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2012/11/02/2751015.html
3. 添加一個視圖
· 原文地址:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2012/11/06/2756711.html
4. 添加一個模型
· 原文地址:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2012/12/17/2821495.html
5. 從控制器訪問數據模型
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2013/01/11/2855935.html
6. 驗證編輯方法和編輯視圖
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2013/01/24/2874622.html
7. 給電影表和模型添加新字段
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2013/02/26/2933105.html
8. 給數據模型添加校驗器
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2013/03/05/2944030.html
9. 查詢詳細信息和刪除記錄
· 譯文地址:http://www.cnblogs.com/powertoolsteam/archive/2013/03/07/2948000.html
10.第三方控件Studio for ASP.NET Wijmo MVC4 工具應用
· 地址:http://www.cnblogs.com/powertoolsteam/archive/2013/05/09/3068699.html
相關閱讀:
微軟 Build 2017 開發者大會:Azure 與 AI 的快速發展