1. 2.Note It's a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data acce
1.
In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutorial you'll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views. 在前面的課程中,你使用Entiey Framework和SQL Server LocalDB創建了一個可以存儲和顯示數據的MVC應用程式。在這一課,你將會複習和自定義,MVC框架為你的控制器和視圖自動創建的增刪查改的功能。
2.Note It's a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data access layer. To keep these tutorials simple and focused on teaching how to use the Entity Framework itself, they don't use repositories. For information about how to implement repositories, see the ASP.NET Data Access Content Map.
註解:通常,我們都會去實現倉儲模式,可以通過在你的控制器和數據訪問層之間創建一個抽象層來實現。為了保持這個課程的簡單,和專註怎麼使用EF本身,我們不使用倉儲模式,要瞭解更多的實現倉儲模式的例子,請看鏈接文章。
In this tutorial, you'll create the following web pages:
在這個課程中,你將會創建下麵的Web頁面:
3.Create a Details Page--創建一個詳細列表頁面
The scaffolded code for the Students Index page left out the Enrollments property, because that property holds a collection. In the Details page you'll display the contents of the collection in an HTML table. 這個MVC框架代碼,為學生列表頁面,預留出了Enrollments屬性,因為這個屬性是一個集合,在詳細列表頁面,你將會以一個HTML表格的形式,來展示集合的內容。 In Controllers\StudentController.cs, the action method for the Details view uses the Find method to retrieve a single Student entity.
// GET: Students/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = db.Students.Find(id); if (student == null) { return HttpNotFound(); } return View(student); }
Route data Route data is data that the model binder found in a URL segment specified in the routing table. For example, the default route specifies controller, action, and id segments: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); In the following URL, the default route maps Instructor as the controller, Index as the action and 1 as the id; these are route data values. http://localhost:1230/Instructor/Index/1?courseID=2021 "?courseID=2021" is a query string value. The model binder will also work if you pass the id as a query string value: http://localhost:1230/Instructor/Index?id=1&CourseID=2021 The URLs are created by ActionLink statements in the Razor view. In the following code, the id parameter matches the default route, so id is added to the route data. @Html.ActionLink("Select", "Index", new { id = item.PersonID }) In the following code, courseID doesn't match a parameter in the default route, so it's added as a query string. @Html.ActionLink("Select", "Index", new { courseID = item.CourseID })
4.
Open Views\Student\Details.cshtml. Each field is displayed using a DisplayFor helper, as shown in the following example: 打開Details頁面,每一個欄位,都使用了DisplayFor輔助方法:黃色的部分是修改的 <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.LastName) </dt> <dd> @Html.DisplayFor(model => model.LastName) </dd> <dt> @Html.DisplayNameFor(model => model.FirstMidName) </dt> <dd> @Html.DisplayFor(model => model.FirstMidName) </dd> <dt> @Html.DisplayNameFor(model => model.EnrollmentDate) </dt> <dd> @Html.DisplayFor(model => model.EnrollmentDate) </dd> <dt> @Html.DisplayNameFor(model => model.Enrollments) </dt> <dd> <table> <tr> <th>Course Title</th> <th>Grade</th> </tr> @foreach (var item in Model.Enrollments) { <td>@Html.DisplayFor(s => item.Course.Title)</td> <td>@Html.DisplayFor(s => item.Grade)</td> } </table> </dd> </dl>
This code loops through the entities in the Enrollments
navigation property. For each Enrollment
entity in the property, it displays the course title and the grade. The course title is retrieved from the Course
entity that's stored in the Course
navigation property of the Enrollments
entity. All of this data is retrieved from the database automatically when it's needed. (In other words, you are using lazy loading here. You did not specifyeager loading for the Courses
navigation property, so the enrollments were not retrieved in the same query that got the students. Instead, the first time you try to access the Enrollments
navigation property, a new query is sent to the database to retrieve the data. You can read more about lazy loading and eager loading in the Reading Related Data tutorial later in this series.)
這個迴圈代碼,通過Enrollments導航屬性,每一個Enrollment實體在這個屬性中,它顯示了課程的標題,和分數。課程的標題是從儲存在enrollments實體的課程寶航屬性中取出來的,所有的這些數據,都是在需要的時候,自動從資料庫中讀取出來的。(換句話說,要瞭解更多懶載入的資料,請看鏈接文章)
Run the page by selecting the Students tab and clicking a Details link for Alexander Carson. (If you press CTRL+F5 while the Details.cshtml file is open, you'll get an HTTP 400 error because Visual Studio tries to run the Details page but it wasn't reached from a link that specifies the student to display. In that case, just remove "Student/Details" from the URL and try again, or close the browser, right-click the project, and click View, and then click View in Browser.)
Update the Create Page--更新新建頁面
In Controllers\StudentController.cs, replace the HttpPost
Create
action method with the following code to add a try-catch
block and remove ID
from the Bind attribute for the scaffolded method:
在Student控制器中,用下麵的代碼代替Create方法,併為Create方法添加異常處理語句,然後移除ID綁定屬性。
// POST: Students/Create // 為了防止“過多發佈”攻擊,請啟用要綁定到的特定屬性,有關 // 詳細信息,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "LastName,FirstMidName,EnrollmentDate")] Student student) { try { if (ModelState.IsValid) { db.Students.Add(student); db.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException /*dex*/) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(student); }
This code adds the Student
entity created by the ASP.NET MVC model binder to the Students
entity set and then saves the changes to the database. (Model binder refers to the ASP.NET MVC functionality that makes it easier for you to work with data submitted by a form; a model binder converts posted form values to CLR types and passes them to the action method in parameters. In this case, the model binder instantiates a Student
entity for you using property values from the Form
collection.)
這個代碼,添加了由ASP.NET MVC 模型綁定創建的Student實體。模型綁定,對應到Student實體中,並且保存到資料庫中。(模型綁定,指的是ASP.NET MVC 的一個功能,它能夠使你更好的通過表單提交數據,模型綁定把表單的值轉化為CLR類型,然後以參數的形式傳遞到Action方法中。這種情況下,模型綁定通過表單集合中的屬性值,實例化了一個Student實體)
You removed ID
from the Bind attribute because ID
is the primary key value which SQL Server will set automatically when the row is inserted. Input from the user does not set the ID
value.
你從模型綁定中,移除了ID低端,因為ID是主鍵,當執行SQL插入操作的時候,會自動的執行,用戶輸入的值中,沒有輸入ID的值。
Security Note: The ValidateAntiForgeryToken
attribute helps prevent cross-site request forgery attacks. It requires a corresponding Html.AntiForgeryToken()
statement in the view, which you'll see later.
The Bind
attribute is one way to protect against over-posting in create scenarios. For example, suppose the Student
entity includes a Secret
property that you don't want this web page to set.
安全提示:ValidateAntiForgeryToken這個屬性,幫助阻止“跨站點請求偽造”攻擊。它需要在View中寫一個Html.AntiForgeryToken()語句,你等會會看到的。
Bind屬性是一個方法,來預防重覆提交(Over-Posting)。例如,假設Student實體中,包含一個Srcret屬性,並且你不想讓,網站去得到它的值。
public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public string Secret { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; }
}
Even if you don't have a Secret
field on the web page, a hacker could use a tool such asfiddler, or write some JavaScript, to post a Secret
form value. Without the Bind attribute limiting the fields that the model binder uses when it creates a Student
instance, the model binder would pick up that Secret
form value and use it to create the Student
entity instance. Then whatever value the hacker specified for the Secret
form field would be updated in your database. The following image shows the fiddler tool adding theSecret
field (with the value "OverPost") to the posted form values.
即使你,你的網站裡面沒有Secret欄位,黑客能夠通過一種工具,例如fiddler,或者寫一些Javascript,來Post一個Secret值,在創建Student實體的時候,使用模型綁定的時候,沒有Bind屬性限制欄位,這個模型綁定竟會找出Secret值,使用它來創建Student實例.然後無論黑客,指定了什麼值,都會被更新到你的資料庫中。
An alternative way to prevent overposting that is preferrred by many developers is to use view models rather than entity classes with model binding. Include only the properties you want to update in the view model. Once the MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such as AutoMapper. Use db.Entry on the entity instance to set its state to Unchanged, and then set Property("PropertyName").IsModified to true on each entity property that is included in the view model. This method works in both edit and create scenarios.
另外一個受很多程式員歡迎的方法,來阻止重覆Post的方法是使用視圖模型而不是實體類,來進行模型綁定。包含你要更新的屬性到視圖模型中,一旦MVC模型綁定完成了,賦值這個視圖模型中的屬性到實體的實例中,通常會選擇一個工具,例如:Automapper,修改實體的狀態為unchanged,然後設置要修改的屬性的IsModified屬性為True。這個方法,在編輯和新建的時候,都有效。
Other than the Bind
attribute, the try-catch
block is the only change you've made to the scaffolded code. If an exception that derives from DataException is caught while the changes are being saved, a generic error message is displayed. DataException exceptions are sometimes caused by something external to the application rather than a programming error, so the user is advised to try again. Although not implemented in this sample, a production quality application would log the exception. For more information, see the Log for insight section in Monitoring and Telemetry (Building Real-World Cloud Apps with Azure).
PS:不重要的,就不翻譯了。。
Update the Edit HttpPost Method--更新編輯的方法
In Controllers\StudentController.cs, the HttpGet
Edit
method (the one without the HttpPost
attribute) uses theFind
method to retrieve the selected Student
entity, as you saw in the Details
method. You don't need to change this method.
在控制器中,找到這個Edit方法(get方式的),它使用了Find方法,來檢索選擇的Student實體,就和你在Details方法中,看到的那樣,你不需要改變這個方法。
However, replace the HttpPost
Edit
action method with the following code:、
用下麵的方法,代替Post方式的Edit方法:
[HttpPost,ActionName("Edit")] [ValidateAntiForgeryToken] public ActionResult EditPost(int?id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var studentTOUpdate = db.Students.Find(id); if (TryUpdateModel(studentTOUpdate, "", new string[] {"LastName","FirstName","EnrollmentDate" })) { try { db.SaveChanges(); return RedirectToAction("Index"); } catch (DataException /*dex */) { ModelState.AddModelError("", "不能保存,請再試"); } } return View(studentTOUpdate); }
These changes implement a security best practice to prevent overposting, The scaffolder generated a Bind
attribute and added the entity created by the model binder to the entity set with a Modified flag. That code is no longer recommended because the Bind
attribute clears out any pre-existing data in fields not listed in the Include
parameter. In the future, the MVC controller scaffolder will be updated so that it doesn't generate Bind
attributes for Edit methods.
這些修改,實現了一個安全機制來阻止重覆Post,這個框架生成了Bind屬性,並且添加了由模型綁定創建的實體,還為其設置了一個Modified的flag,這個代碼不再被推薦了,因為Bind屬性,清除了所有之前不再Include參數列表中的已存在的數據,在將來,MVC框架會升級,將不會為Edit方法生成Bind屬性。
The new code reads the existing entity and calls TryUpdateModel to update fields from user input in the posted form data. The Entity Framework's automatic change tracking sets the Modified flag on the entity. When the SaveChangesmethod is called, the Modified
flag causes the Entity Framework to create SQL statements to update the database row. Concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn't change. (A later tutorial shows how to handle concurrency conflicts, and if you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified.)
As a best practice to prevent overposting, the fields that you want to be updateable by the Edit page are whitelisted in the TryUpdateModel
parameters. Currently there are no extra fields that you're protecting, but listing the fields that you want the model binder to bind ensures that if you add fields to the data model in the future, they're automatically protected until you explicitly add them here.
As a result of these changes, the method signature of the HttpPost Edit method is the same as the HttpGet edit method; therefore you've renamed the method EditPost.