asp.net MVC Development To delete modify data _ practical Tips

Source: Internet
Author: User

The previous article described asp.net mvc using EF to query data and deferred loading of data by dbquery<t> generic objects in EF. Today we'll see how we can use EF to delete data.

In fact, the common mode of web development now is the front-end use of JS and jquery to the back-end data interaction. So we're going to add two deleted and updated scripts on the front end. The code is as follows:

<!--traversal action method set to ViewData collection data, generate HTML code-->
      @foreach (blogarticle A in viewdata["DataList"] as list< blogarticle>)
      {
        <tr>
          <td>@a.AId</td>
          <td>@a.ATitle</td>
          <td>@a.BlogArticleCate.Name</td>
          <td>@a.Enumeration.e_cname</td>
          <td>@a. Aaddtime</td>
          <!---------Add the Delete button--------->> <td><a href= Javascript:del for the list of articles
          (@a . 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?") ")" {

<!--This configuration when the user determines the deletion, JS lets the page jump to the URL address-->
        window.location= "/home/del/" + ID
      ;
    }
  </script>

The JS code above means that when the user clicks on the delete button, the URL jump address is "/home/del" +id

Before clicking the effect below the image, note that the URL address is

It means that browsers now request the controller (Controller) based on routing, the Controller returns the view method according to the routing configuration, and then attempts to pass the Html,js back to the browser.

Click the Delete button and OK, note that the URL address is

Indicates that the routing information we configured is "Home/del"

So 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 MVC Default routing table configuration, the RouteConfig.cs under the App_start folder, and the following code:

Routing table configuration public
  class Routeconfig
  {public
    
    static void RegisterRoutes (RouteCollection routes)
    {
      Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

      Routes. Maproute (
        name: "Default",
        URL: "{controller}/{action}/{id}",
        defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}
      );
    }
  
 

We can see that your default configuration mode is "{Controller}/{action}/{id}"

The default configuration information is defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}

The special note is that id = urlparameter.optional is optional.

So we should create a Del-type action method in HomeController.cs with the following code:

 Delete Article public
    actionresult Del (int id)
    {
      //Operation database use Try...catch to catch exception
      try
      {
        //Create Delete object
        Blogarticle artticle = new Blogarticle ();
        Artticle.aid = ID;
        Adds a Delete object to the EF Object Management container
        db. Blogarticles.attach (artticle);
        Identifies the state of the object wrapper class as deleting State
        db. Blogarticles.remove (artticle);
        Update to database
        db. SaveChanges ();
        After the update succeeds, the page jumps to the index page return
        redirecttoaction ("Index", "Home");
      }
      catch (Exception ex)
      {return
        redirecttoaction ("friendly page");
      }
      return View ();
    }

This completes the delete operation of the data.

Next we'll complete the modified code, and we'll show the view code as follows

 <!--generate a form and indicate the form submission method, and Route--> @using (Html.BeginForm ("Modify", "Home", FormMethod.Post)) {<table id= "t
      Blist "> <tr> <td colspan=" 2 "> Modify @Html. hiddenfor (a=>a.aid) </td> </tr> <tr> <td> title:</td> @*<td> @Html. TextBox ("Txtname", (object) model.atitle) &LT;/TD&G t;*@ <!--generate text boxes--> <td> @Html directly from Model based on the Atitle property using the strongly typed method of HtmlHelper. Textboxfor (a=>a.at Itle) </td> </tr> <tr> <td> Classification:</td> <!--use a strongly typed method to generate a Drop-down box and automatically follow mod The acate value in the El property sets the default check for the Drop-down box--> <td> @Html. Dropdownlistfor (a=>a.acate,viewbag.catelist as Ienumerable<s electlistitem>) </td> </tr> <tr> <td> content:</td> <!--use Htmlhel The strongly typed method of per is to generate text field--> <td> @Html directly from Model according to the Acontent property. Textareafor (a => a.acontent, a, NULL) < /TD> </tr> <tr> <td colspan= "2" ><input type= "Submit" value= "Confirm modification"/> @Html. ActionLink ("Back", "Index", "Home") &

 Lt;/td> </tr> </table>}

How do we write back-end code?

Because our action is executed when the expression is submitted as post, the///<summary>///load needs to be amended to add the article///</summary> <param name= "id" > need to modify the article id</param>///<returns></returns> public ActionResult Edita rticle (int id) {//Get the article that needs to be edited and return the first element of the entity object blogarticle art = (from C in DB. Blogarticles where c.aid = = ID Select c).
      
      FirstOrDefault (); We make a drop-down list of the articles, and give the Droplist <option> assignment ienumerable<selectlistitem> Selelistitem = (from a in db. blogarticlecates where A.isdel = = False Select a). ToList ().

      Select (a => new SelectListItem {Value = a.id.tostring (), Text = A.name});

      Returns the list object viewbag.catelist = Selelistitem;
    return View (); The next step is to execute the modified code: [HttpPost]///<summary>///Execute the modified code///</summary>///<param name= "model" ></param>///<returns></returns> public actionresult Modify (blogarticle model) {T ry {
        1. Add entity object A. To the EF object container, and B. Gets the pseudo wrapper class object dbentityentry<blogarticle> entry = db.
        Entry<blogarticle> (model); 2. Set the state of the wrapper class object to unchanged entry.
        state = System.Data.EntityState.Unchanged; 3. Set the Changed property entry. Property (a => a.atitle).
        IsModified = true; Entry. Property (a => a.acontent).
        IsModified = true; Entry. Property (a => a.acate).

        IsModified = true; 4. Submit to database to finish modifying db.
        SaveChanges ();
      5. The update succeeds, the command browser redirects to the/home/list method return Redirecttoaction ("Index", "Home"); catch (Exception ex) {return Content ("Modify failed ~ ~ ~" + ex.)
      message); 

 }
    }

We have completed the task of using MVC to build a small site, and have completed the operation of adding and deleting data.

I hope this article will help you to learn.

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.