你的位置:首页 > ASP.net教程

[ASP.net教程]实现基本的增删查改功能


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 dataRoute 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=2021The 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.