ASP. NET Mvc development-delete and modify data, asp. netmvc

Source: Internet
Author: User

ASP. NET Mvc development-delete and modify data, asp. netmvc

The previous article introduced ASP. net mvc's use of EF to query data and delayed loading of data by EF DbQuery <T> generic objects. Today, let's take a look at how we use EF to delete data.

In fact, the common Web development model is that the front-end uses Js and JQuery to interact with the back-end data. Then we add two Delete and update scripts to the front end. The Code is as follows:

<! -- Traverse the set data set to ViewData by the Action method and generate the HTML code --> @ foreach (BlogArticle a in ViewData ["DataList"] as List <BlogArticle>) {<tr> <td> @. AId </td> <td> @. ATitle </td> <td> @. blogArticleCate. name </td> <td> @. enumeration. e_cname </td> <td> @. AAddtime </td> <! --------- Add delete button for the article list --------- >>< td> <a href = "javascript: del (@. AId) "> Delete </a> </td> </tr>}

Then write the Js script function for the button. The Code is as follows:

<Script type = "text/javascript"> function del (id) {if (confirm ("are you sure you want to delete it? ") {<! -- Configure the url address that js redirects to when the user is sure to delete the page --> window. location = "/home/del/" + id ;}</script>

The above Js code means that when you click the delete button, the url jump address is "/home/del" + id

The effect before clicking is as shown in. Note that the url address is

It means that the browser requests the Controller Based on the route. The Controller returns the view method based on the route configuration, and then tries to return the Html and Js methods to the browser.

Click Delete and confirm. Note that the url address is

The route information we configured is "home/del"

Therefore, we add a del Method to the Controller's HomeController to complete the delete operation. The Code is as follows:

First, let's take a look at the default MVC route table configuration, In the RouteConfig. cs under the App_Start folder, the Code is as follows:

// Configure public class RouteConfig {public static void RegisterRoutes (RouteCollection routes) {routes in the route table. ignoreRoute ("{resource }. axd/{* pathInfo} "); routes. mapRoute (name: "Default", url: "{controller}/{action}/{id}", defaults: new {controller = "Home", action = "Index ", id = UrlParameter. optional });}}

We can find that ur's default configuration mode is "{controller}/{action}/{id }"

The default configuration information is ults: new {controller = "Home", action = "Index", id = UrlParameter. Optional}

Note that id = UrlParameter. Optional is Optional.

Therefore, create a del-type Action method in homeController. cs. The Code is as follows:

// Delete the article public ActionResult Del (int id) {// use try to operate the database... catch to catch exceptions try {// create and delete object BlogArticle artTicle = new BlogArticle (); artTicle. AId = id; // Add the deleted object to the EF Object Management container db. blogArticles. attach (artTicle); // identifies the status of the object packaging class as deleted db. blogArticles. remove (artTicle); // update to database db. saveChanges (); // After the update is successful, the page jumps to the Index page return RedirectToAction ("Index", "Home");} catch (Exception ex) {return RedirectToAction ("friendly page") ;}// return View ();}

This completes the data deletion operation.

Next, we will complete the modified Code. First, we will show the View Code as follows:

<! -- Generate a form and specify the form submission method and route --> @ using (Html. beginForm ("Modify", "Home", FormMethod. post) {<table id = "tbList"> <tr> <td colspan = "2"> modify @ Html. hiddenFor (a =>. AId) </td> </tr> <td> title: </td> @ * <td> @ Html. textBox ("txtName", (object) Model. ATitle) </td> * @ <! -- Use the strong HtmlHelper method to generate a text box directly from the Model based on the ATitle attribute --> <td> @ Html. textBoxFor (a =>. ATitle) </td> </tr> <td> category: </td> <! -- Use the strong type method to generate a drop-down box, and automatically set the default option of the drop-down box according to the ACate value in the model attribute --> <td> @ Html. dropDownListFor (a =>. ACate, ViewBag. cateList as IEnumerable <SelectListItem>) </td> </tr> <td> content: </td> <! -- Use the strong HtmlHelper method to generate a text field from the Model based on the AContent attribute --> <td> @ Html. textAreaFor (a =>. AContent, 10, 60, null) </td> </tr> <td colspan = "2"> <input type = "submit" value = "confirm to modify"/> @ Html. actionLink ("return", "Index", "Home") </td> </tr> </table>}

How can we compile our back-end code change?

// Because our Action is executed during post submission, therefore, add the [HttpGet] // <summary> /// load the document to be modified /// </summary> /// <param name = "id"> to modify the document </param> /// <returns> </returns> public ActionResult EditArticle (int Id) {// obtain the article to be edited and return the first element BlogArticle art = (from c in db. blogArticles where c. AId = id select c ). firstOrDefault (); // we classify the document into a drop-down list and assign the <option> IEnumerable <SelectListItem> seleListItem = (f Rom a in db. blogArticleCates where. isDel = false select ). toList (). select (a => new SelectListItem {Value =. id. toString (), Text =. name}); // returns the List object ViewBag. cateList = seleListItem; return View () ;}the following code is executed: [HttpPost] /// <summary> /// execute the modified Code // </summary> /// <param name = "model"> </param> // /<returns> </returns> public ActionResult Modify (BlogArticle model) {try {// 1. object. join EF In the object container, and B. obtain the pseudo-packaging Class Object DbEntityEntry <BlogArticle> entry = db. entry <BlogArticle> (model); // 2. set the status of the packaging class object to unchanged entry. state = System. data. entityState. unchanged; // 3. set the changed attribute entry. property (a =>. ATitle ). isModified = true; entry. property (a =>. AContent ). isModified = true; entry. property (a =>. ACate ). isModified = true; // 4. submit to database to complete database modification. saveChanges (); // 5. if the update is successful, the command browser redirects to the/Home/List method return. RedirectToAction ("Index", "Home");} catch (Exception ex) {return Content ("modification failed ~~~ "+ Ex. Message );}}

At this point, we have completed the task of creating a small site using MVC, and also completed the addition, deletion, modification, and query of data.

I hope this article will help you learn more.

Articles you may be interested in:
  • Add and modify data in asp.net Confucius cms
  • Asp.net adds, modifies, deletes, and queries the database code.
  • Asp.net Delete and update database Methods
  • Asp.net does not use the built-in delete function of the GridView to delete a row of data.
  • A specific instance of the Data Binding and row-selection deletion function of the DataGridView in ASP. NET

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.