實現基本的增刪查改功能

来源:http://www.cnblogs.com/caofangsheng/archive/2016/03/17/4696927.html
-Advertisement-
Play Games

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 Studententity 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 Studententity 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 Includeparameter. 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. 

 


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

-Advertisement-
Play Games
更多相關文章
  • asp.net 編譯錯誤類型“同時存在於”不同的dll中. 出現這種錯誤大概有三種情況: 1、ASPX頁面,一個*.ASPX,對應著一個*.cs文件,兩者其實是一個文件,通過兩者實現代碼分離,每個*.aspx頁面都引用著自身的CS文件:如果兩個頁面引用了相同得.CS文件,在發佈得時候也會出現這種錯誤
  • 普通電腦沒有通用的輸入輸出口(GPIO),但有時候我就想輸入一個開關量。 比如讓用戶拉一下拉繩開關就啟動某個應用,比如裝一個觸點開關判斷門是打開的還是關閉的,比如.... 需求是如此簡單,你都不願意花幾十塊錢去買一個單片機,更不用說PCI擴展卡、PLC之類的了。。怎麼辦吶? 有辦法!最簡單的用串口就
  • 運行-cmd,輸入下麵命令:C:\WINDOWS\Microsoft.NET\Framework\v版本號\aspnet_regiis.exe -i即可 以下是aspnet_regiis.exe參數的說明信息: -i - 安裝 ASP.NET 的此版本,並更新 IIS 元資料庫根處的腳本映射和根以下
  • 使用ASP.NET模版生成HTML靜態頁面並不是難事,主要是使各個靜態頁面間的關聯和鏈接如何保持完整。本文介紹了使用ASP.NET模版生成HTML靜態頁面的五種方案。 ASP.NET模版生成HTML靜態頁面方案1: 你可以用這個函數獲取網頁的客戶端的html代碼,然後保存到.html文件里就可以了。
  • 泛型是CLR和編程語言提供的一種特殊機制,它用於滿足“演算法重用” 。 可以想象一下一個只有操作的參數的數據類型不同的策略模式,完全可以用泛型來化為一個函數。 以下是它的優勢: 這就是為什麼List<T>淘汰了ArrayList的原因,特別是在進行值類型操作時,因為裝箱拆箱過多而差距很大。 約定:泛型
  • 本篇體驗ASP.NET Web API的安全管道。這裡的安全管道是指在請求和響應過程中所經歷的各個組件或進程,比如有IIS,HttpModule,OWIN,WebAPI,等等。在這個管道中大致分兩個階段,一個是驗證階段,另一個是授權階段。在ASP.NET Web API v1版本的時候,安全管道大致
  • 1. 【二進位(0~1)、八進位(0~7)、十進位(0~9)】→十六進位(0~15,10~15→A~F) 101011→1*20+1*21+0*22+1*23+0*24+1*25=1+2+0+8+0+32=43 053→3*80+5*81=3+40=43 0x2B=B*160+2*161=11+32
  • In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutor
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...