編輯 - 控制器部分

 // GET: Student/Edit/5
 // It is receives a get http request for the controller Student and Action Edit with the id of 5
    public ActionResult Edit(int? id)
    {
         // it good practice to consider that things could go wrong so,it is wise to have a validation in the controller
        if (id == null)
        {
            // returns a bad request
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        
        // It finds the Student to be edited.
        Student student = db.Students.Find(id);
        if (student == null)
        {
            // if doesn't found returns 404
            return HttpNotFound();
        }
        // Returns the Student data to fill out the edit form values.
        return View(student);
    }

此方法與詳細操作方法非常相似,後者是重構的良好候選方法,但它超出了本主題的範圍。

    // POST: Student/Edit/5
    [HttpPost]

    //used to To protect from overposting attacks more details see http://stackoverflow.com/documentation/asp.net-mvc/1997/html-antiforgerytoke
    [ValidateAntiForgeryToken]

    //Represents an attribute that is used for the name of an action.
    [ActionName("Edit")]
    public ActionResult Edit(Student student)
    {
        try
        {
            //Gets a value that indicates whether this instance received from the view is valid.
            if (ModelState.IsValid)
            {
                // Two thing happens here:
                // 1) db.Entry(student) -> Gets a DbEntityEntry object for the student entity providing access to information about it and the ability to perform actions on the entity.
                // 2) Set the student state to modified, that means that the student entity is being tracked by the context and exists in the database, and some or all of its property values have been modified.
                db.Entry(student).State = EntityState.Modified;

                // Now just save the changes that all the changes made in the form will be persisted.
                db.SaveChanges();

                // Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action, in this case the index action.
                return RedirectToAction("Index");
            }
        }
        catch
        {
            //Log the error 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 the invalid student instance to be corrected.
        return View(student);
    }