MVC5 + EF6 + Bootstrap3 (13) View Details, edit data, and delete data, mvc5ef6

Source: Internet
Author: User

MVC5 + EF6 + Bootstrap3 (13) View Details, edit data, and delete data, mvc5ef6

Slark. NET-blog Park http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-rud.html

Series of tutorials: MVC5 + EF6 + Bootstrap3

Previous section: MVC5 + EF6 + Bootstrap3 (12) New Data

Download source code: Click here to download

Directory
  • Preface
  • Add Link
  • View Details
  • Edit data
  • Delete data
  • End
Preface

The preceding section describes how to query pages and how to create data. As we have made a lot of preparations before, this section will be able to smoothly show you all the details, edit data, and delete data. The preceding and following sections add up all the operations for adding, deleting, modifying, and querying (CRUD) of a simple information system.

Add Link

To perform these three operations, add the corresponding link after each record on the query page. The Code is as follows:

<tr>    <td>        @Html.DisplayFor(modelItem => item.FirstName)    </td>    <td>        @Html.DisplayFor(modelItem => item.LastName)    </td>    <td>        @Html.DisplayFor(modelItem => item.Sex)    </td>    <td>        @Html.DisplayFor(modelItem => item.Rating)    </td>    <td>        @Html.ActionLink("Details","Details", new { id = item.ID }) |         @Html.ActionLink("Edit", "Edit" , new { id = item.ID }) |         @Html.ActionLink("Delete", "Delete", new { id = item.ID })    </td></tr>

The code above corresponds to a row in the data list. The yellow part is the link we added. These three links correspond to three different operations. They all need IDs as parameters to determine which data to operate. The changed page is shown as follows:

1 public ActionResult Details (int? Id) 2 {3 if (id = null) 4 {5 return new HttpStatusCodeResult (HttpStatusCode. badRequest); 6} 7 Worker worker = db. workers. find (id); 8 if (worker = null) 9 {10 return HttpNotFound (); 11} 12 return View (worker); 13}

Row 3-6 indicates that if the parameter id is not provided when the Actions is accessed, the BadRequest error is returned. As shown in, no ID is provided in the address bar, and the Bad Request error is returned.

1 @ model SlarkInc. models. worker 2 @ {3 ViewBag. title = "Details "; 4} 5

The DisplayNameFor function is used in the code to display the attribute name, And the DisplayFor function to display the attribute value.

The page uses the <dl> <dt> <dd> and Bootstrap's "dl-horizontal" class layout page to make each attribute name and attribute value take one row. The following figure shows the effect:

Public ActionResult Edit (int? Id) {if (id = null) {return new HttpStatusCodeResult (HttpStatusCode. badRequest);} Worker worker = db. workers. find (id); if (worker = null) {return HttpNotFound ();} return View (worker );}

Looks familiar? That's right. It's exactly the same as the Details Action. It won't be repeated here.

Write the View below. In ~ Create the Edit. cshtml view under \ Views \ Company \. Write the following code:

 1 @model SlarkInc.Models.Worker 2 @{ 3     ViewBag.Title = "Edit"; 4 } 5 

The code for this page is basically the same as the code for inserting data pages in the previous section. You can refer to the code description in the previous section.

Row 3 uses the HiddenFor function to store the ID of the record to be modified so that the corresponding record can be found and updated after submission.

The page is displayed as follows:

1 [HttpPost] 2 [ValidateAntiForgeryToken] 3 public ActionResult Edit ([Bind (Include = "ID, FirstName, LastName, Sex, Rating")] Worker worker) 4 {5 if (ModelState. isValid) 6 {7 db. entry (worker ). state = EntityState. modified; 8 db. saveChanges (); 9 return RedirectToAction ("Index"); 10} 11 return View (worker); 12}

The knowledge points with codes are basically the same as those in the previous Create submit Action section. Click here to view details.

The difference is that there are 7th rows. Based on the obtained worker instance, find the corresponding record in the data list, update its value, and set its status to Modified. Save the changes to the database and go back to the Data Query page.

Delete data

To Delete data, you do not need to display data on the page. You only need to add a Delete Action under CompanyController to Delete the data. The Code is as follows:

 1 public ActionResult Delete(int id) 2 { 3     try 4     { 5         Worker workerToDelete = new Worker() { ID = id }; 6         db.Entry(workerToDelete).State = EntityState.Deleted; 7         db.SaveChanges(); 8     } 9     catch(DataException/*dex*/)10     {11         return RedirectToAction("Index", new { id = id, saveChangesError = true });12     }13     return RedirectToAction("Index");14 }

Create a worker instance with only the ID assigned to it in row 5th. Then, Row 3 finds the corresponding data in the database based on the instance ID, sets its status to Deleted, and row 3 deletes the data.

If the deletion is successful, the query page will be displayed on line 1. If the deletion fails, the query page will be redirected and the failure record ID and saveChangesError = true will be passed through two parameters. Based on these two parameters, you can write error messages on the query page. This is not detailed here.

In this way, you can click the delete link to view the deleted data on the query page.

End

At this point, we have completed adding, deleting, modifying, and querying a simple data model. However, there are still many knowledge points that are not described in detail, such as data verification, EF data operation functions, various Http responses in the View, and so on. We will introduce it in detail later.

If it is useful, we recommend it!

This section mainly references: Implementing Basic CRUD Functionality with the Entity Framework in ASP. net mvc Application

Previous section: MVC5 + EF6 + Bootstrap3 (12) New Data

Author:Slark. NET

Source: http://www.cnblogs.com/slark/

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable. If you have any questions or suggestions, please give me some further information. Thank you very much.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.