Confirming Delete Operations in ASP.NET MVC

Introduction

Seeking confirmation of some important action, such as deleting a record, is a common practice in web applications. There are two common approaches to seek confirmation from the end user. In the first approach a dialog box is displayed to the user seeking his consent to perform the delete operation and in the second approach the user is shown a separate confirmation page. In the former approach the control remains in the page where deletion is taking place whereas in the latter case control moves to a confirmation page and the actual deletion operation happens in the confirmation page. This article illustrates how both of these techniques can be implemented in ASP.NET MVC.

Which Technique to Use?

As discussed earlier there are two common ways to seek confirmation of a delete operation from the user :

  • Show a dialog box to the end user seeking his consent for the delete operation
  • Take the user to a confirmation page where he confirms the delete operation

Though there is no rigid rule as to which technique you should use, generally the first technique is used when the user is not supposed to review the entire record being deleted. Consider, for example, that you are working with an order processing system and there is a web page showing a list of past orders. Now the listing page might be showing only the partial information about the order. If a user deletes an order without reviewing the complete details of the order chances are that he is unaware of possible consequences of deleting the record. It would be desirable that he is presented with the complete order history along with notes, comments and special instructions about the order before he deletes it. In such cases the first way of confirming deletes is inadequate and you might prefer to use the second technique. The second technique may also be required in situations where you wish to use a minimum or no client side script.

Creating a Sample Application

In order to illustrate both of the techniques discussed above, you will develop a sample ASP.NET MVC application. To begin with, create an empty ASP.NET MVC application using ASPX view engine. The sample application will use the Employees table from the Northwind database and you will need to create an Entity Framework data model for the same. So, add a new ADO.NET Entity Data Model in the Models folder and then drag and drop the Employees table on it. Doing so will create a model as shown below :

Add a new ADO.NET Entity Data Model
Figure 1: Add a new ADO.NET Entity Data Model

Confirming Deletes Without Leaving the Current Page

Once the data model is ready add a new controller class and name it Home. Add an action method - Index() - as shown below :

public ActionResult Index()

{

    NorthwindEntities db=new NorthwindEntities();

    var data = from item in db.Employees

                select item;

    ViewBag.Employees = data;

    return View();

}

As you can see, the Index() action method fetches all of the employees and stores the collection in a ViewBag property (Employees). Then right click on the Index() action method and add a view named Index. The Index view will display all of the employee records and will have links to delete a record. The Index view as shown in the browser looks like this :

Index View of Employee Listing
Figure 2: Index View of Employee Listing

The HTML markup of Index view is shown below :

<h2>Employee Listing</h2>

<%

using (Html.BeginForm()){

%>

<table border="1" cellpadding="5">

<% 

foreach(var item in ViewBag.Employees)

{

%>

<tr>

<td><%= item.EmployeeID %></td>

<td><%= item.FirstName %></td>

<td><%= item.LastName %></td>

<td><%= Html.ActionLink("Delete", "Delete", new { @employeeid = item.EmployeeID }, new { @class="delete", @id=item.EmployeeID })%></td>

</tr>

<%

}

%>

</table>

<%

}

%>

As you can see, the view essentially renders a table and displays FirstName and LastName columns. It also renders a hyperlink to initiate the delete operation. Notice that ID attribute of the hyperlink is set to EmployeeID so that you can detect the employee ID to be deleted later in the code. Also, the hyperlink is assigned a CSS class named delete. This is done so that your client side code can distinguish delete hyperlinks from rest of the hyperlinks from the page.

Next, add an action method - DeleteAJAX() - that deletes a specified employee record as shown below :

[HttpPost]

public JsonResult DeleteAJAX(int employeeid)

{

  NorthwindEntities db = new NorthwindEntities();

  Employee data = (from item in db.Employees

                   where item.EmployeeID == employeeid

                   select item).SingleOrDefault();

  db.Employees.DeleteObject(data);

  db.SaveChanges();

  return Json("Record deleted successfully!");

}

The DeleteAJAX() action method is intended to be called from client side jQuery code and hence its return type is JsonResult. Inside, it deletes an employee record based on the EmployeeID passed to it and returns a string message to the caller.

In this technique you will be using jQuery to call the DeleteAJAX() action method. So, add a script reference to jQuery library.

<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>

Then add a script block and write the following code in it :

    <script type="text/javascript">

        $(document).ready(function () {

            $('a.delete').click(OnDeleteClick);

        });

 

        function OnDeleteClick(e)

        {

            var employeeId = e.target.id;

            var flag = confirm('You are about to delete Employee ID ' + employeeId + ' permanently. 

                                Are you sure you want to delete this record?');

            if (flag) {

                $.ajax({

                    url: '/home/DeleteAJAX',

                    type: 'POST',

                    data: { employeeid: employeeId },

                    dataType: 'json',

                    success: function (result) { alert(result); $("#" + employeeId).parent().parent().remove(); },

                    error: function () { alert('Error!'); }

                });

            }

            return false;

        }

    </script>    

The ready() function wires click the event handler of the delete hyperlinks to the OnDeleteClick function. Notice how the delete hyperlinks are filtered using the class name we assigned earlier. The OnDeleteClick() function retrieves the ID of the delete link being clicked, using the target.id property. It then seeks confirmation from the user using the confirm() JavaScript function. If the user clicks on OK, an AJAX call is made to the DeleteAJAX() action method using jQuery $.ajax(). Notice how the options of $.ajax() are specified. The url parameter indicates the URL of the action method to be called, type parameter specifies the method to be used (POST) for calling the action method. The data parameter is the JSON representation of the employee ID to be deleted. Recollect that employeeid is the parameter name of the DeleteAJAX() action method. When the remote action method completes successfully a function, as specified by the success parameter, will be called. In the above example, the success function simply displays the message as returned by the DeleteAJAX() method. The concerned table row is then removed using the remove() method. This way the deleted record will be removed from the table. Notice the use of the parent() method. Since the delete hyperlink is inside a <td> which is inside a <tr> you need to use it twice to remove the table row.

Now, run the index view and try deleting a record. The following figure shows the index view after a delete attempt.

The index view after a delete attempt
Figure 3: The index view after a delete attempt

Confirming Deletes by Navigating to a Confirmation Page

In the second technique of confirming deletes you will display an intermediate confirmation page before deleting a record. In order to implement this technique you need to add the following two action methods in the Home controller.

public ActionResult ConfirmDelete(int employeeid)

{

    NorthwindEntities db=new NorthwindEntities();

    var data = from item in db.Employees

                where item.EmployeeID == employeeid

               select item;

    Employee employee = data.SingleOrDefault();

    return View(employee);

}

 

[HttpPost]

public ActionResult Delete(int employeeid)

{

    NorthwindEntities db = new NorthwindEntities();

    Employee data=(from item in db.Employees

                where item.EmployeeID == employeeid

                select item).SingleOrDefault();

    db.Employees.DeleteObject(data);

    db.SaveChanges();

    return View();

}

In the previous example you called the DeleteAJAX() method directly from the client side code. In this case the delete operation will not happen from the employee listing page. When a user clicks on the delete link, he will be taken to the ConfirmDelete view wherein delete confirmation is sought. On the delete confirmation page you will display details such as EmployeeID, FirstName, LastName and Notes so that the user can review the record being deleted. The ConfirmDelete() action method essentially retrieves an employee's information and passes it to the ConfirmDelete view. The ConfirmDelete view then calls the Delete() action method if the user decides to delete that record. The Delete() action method simply deletes an employee record from the database.

After completing the ConfirmDelete() and Delete() action methods, right click on them one by one and add the respective views. While creating the ConfirmDelete view make sure to create a strongly typed view based on Employee class.

ConfirmDelete
Figure 4: ConfirmDelete

The following figure and HTML markup shows what the ConfirmDelete view looks like.

ConfirmDelete View
Figure 5: ConfirmDelete View

<% using (Html.BeginForm("Delete", "Home", FormMethod.Post))

{

%>

<h2>Warning!</h2>

You are about to delete the following Employee record :

<br /><hr />

<strong>

<%= Model.EmployeeID + ". " + Model.FirstName + " " + Model.LastName %>

<br />

<%= Model.Notes %>

</strong>

<br/><hr />

Are you sure you want to delete this record?

<br/>

<%= Html.HiddenFor(m => m.EmployeeID)%>

<input type="submit" value="Delete" />

<input type="button" value="Cancel" onclick="OnCancelClick();" />

<%} %>

As you can see, the ConfirmDelete view receives an employee instance as a Model. It then displays EmployeeID, FirstName, LastName and Notes. Notice that the HTML form will be submitted to the Delete() action method as indicated in the BeginForm(). Also notice the use of a hidden form field for storing EmployeeID. This way when the form is submitted the Delete() action method will receive the EmployeeID to be deleted. Clicking on the Cancel button will call a JavaScript function OnCancelClick() that will simply take the user to the employee listing page. The OnCancelClick() function is shown below.

 function OnCancelClick() {
     window.location.href = '/home/index';
}

The ConfirmDelete action method needs to be wired with the Delete hyperlinks of the Index view. So, modify the ActionLink() call that renders the Delete link as follows :

<%= Html.ActionLink("Delete","ConfirmDelete",new { @employeeid = item.EmployeeID })%>

The Delete view simply displays a message informing successful record deletion.

Record Deleted
Figure 6: Record Deleted

 <h2>Record Deleted!</h2>

<%= Html.ActionLink("Back to Employee Listing", "Index") %>

That's it! Now run the Index view and click on any of the Delete links. You will be taken to the ConfirmDelete view wherein you can delete the record. 

Summary

Seeking confirmation from the user prior to deleting a record is a common practice in web applications. There can be multiple ways to implement this functionality in a web page. This article covered two popular techniques of confirming deletes in an ASP.NET MVC application. You can customize or modify the techniques illustrated here to suit your requirements.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles

Downloads

Comments

  • What does "back To Employee Listing" Do?

    Posted by FanFarron on 03/25/2014 11:21am

    The view contains this : "Html.ActionLink("Back to Employee Listing", "Index")" However, if you were to click on the link, the listing would then be displayed in that window right? That is, the original window where the user clicked to get to the Delete Confirmation window is no longer accessible. I am looking for a way that upon completion of the deletion, control could be returned to the original window. I am using MVC4 for my application. Any feedback/guidance/comments would be greatly appreciated.

    Reply
  • Hovedtelefoner isnot bare et headset, er et vindue til at se verden

    Posted by mbakeb971 on 07/16/2013 08:36pm

    One caveat: The Zoro does not hold up well to repeated high volume usage on deep bass tracks that cause distortion. As with many pairs in the $100-range, this eventually seems to lead to some permanent driver damage. It doesn’t mean the headphones will be unusable, but they might suffer from a bit of rattling or fuzziness on certain frequencies, regardless of the volume—at the end of our testing, a third deep bass, high volume test ended up doing some damage to the right ear’s drivers. [url=http://beatsbydrdredanmark.weebly.com/]Beats by dre Hovedtelefoner[/url] Man skal også kigge efter den ekstraordinære træk ved støj isolation i deres trådløse hovedtelefoner som en måde at tage glæde i høj kvalitet musik. Begrebet støj isolation er ikke det samme som at billige beats lady gaga By Dre Detox Special Limited Edition Professional Headphones Canada af støjdæmpning. Funktionen af støj isolation gør det muligt for ikke en eneste plet af eventuelle baggrundslyde, som en individuel taler ved siden af billige dre beats dig at blande i din lytning. Dette virkelig er utroligt så langt som du er nødt til at groove i dine egne betingelser. Det er hævet over enhver tvivl, at omdømme i de trådløse hovedtelefoner er på himmelflugt med hver eneste dag, der går. Så er du i øjeblikket i stand til at købe beats af Lady Gaga din første trådløse hovedtelefoner til tv? Forhåbentlig er du, fordi det ville være en skam at gå glip af alle de fremragende programmer og film, som kan blive lyttet til i det antal, du foretrækker simpelthen fordi du ikke har oprettet dine tanker dog. beats by dresolo hd til virkelig at føle meget mere behageligt, gøre bare lidt længere at lede efter de funktioner, du ønsker. Meget bedre endnu, kan du besøge en forhandler og teste nogle ud. Så vil du virkelig føle sig helt sikker, som du er parat til ikke bare købe, men beats by Lady Gaga helt sikkert sætte pris en helt ny trådløs hovedtelefon til fjernsyn. [urlhttp://beatsbydredanmark.webspawner.com/]Beats by Dre[/url] Jeg har efterhånden været indehaver af dette pragteksemplar i knap ét og jeg nyder hvert et øjeblik i selskab med mine Beats. Der er ingen tvivl om, at de har taget verden med storm og de er kommet for at blive. Det kan tage lang tid at finde det rette headset, men med disse Beats by Dr. Dre Studio er jeg tydeligvis ikke gået galt i byen på noget tidspunkt. Hverken i forhold til min stationær,

    Reply
  • GHD riche rubis rouge cadeau réglé finition brillante à votre style

    Posted by carpinteyrobme on 07/16/2013 12:18am

    Le redresseur a un attachement de fil en rotation et trois réglages de température différents pour les différentes caractéristiques et les types de cheveux, où la température maximale est de 230 ° convertisseur de tension globale C.Med pour 120-240V est le redresseur trop parfait pour avoir le voyage, et de le stocker en toute sécurité dans le sac résistant à la chaleur inclus dans luxe design.Elegant redresseurs Paris que vous pouvez à la fois les cheveux lisses et boucle avec. [url=http://ghdpascherferfr.webgarden.com/]ghd lisseur[/url] Est-ce vrai, beaucoup de gens achèteront seulement un redresseur et pas de shampooing et de produits complémentaires. Donc, je ne suis pas sûr de savoir comment cela fonctionne comme une stratégie d'entreprise à long terme, une chose est sûre cependant, c'est que le consommateur est certainement bénéficier de ces marques connues prices.Some réduits sont moins chers, Revlon et Remington, offrant un très bon choix en des alternatives moins chères. Bien qu'ils ne peuvent toujours pas être classés comme pas cher que vous pourriez espérer, mais ils sont encore à moitié prix marque GHD. Ils sont aussi faites de plaques en céramique et tourmaline. Cela verrouille à l'humidité dans vos cheveux et ne se dessèche pas. Ces produits sont excellents car ils sont à double usage, pour le redressage et le curling, ils ne seront pas endommager vos cheveux et céramique dure beaucoup plus longtemps que l'aluminium fait. [url=http://ghdpascherferfr.blinkweb.com/]ghd pas cher lisseur[/url] Le ressort de la boutique, il est beaucoup Cheap GHD Norge.Our lisseur ghd pas seulement pas cher mais la qualité est Veldig soutien-gorge, est la meilleure product.These ghd pas cher du monde a Flot différent versjoner av ghd stylers cheveux y hjelpe skjønnhet bevisst en y Öppna son Utseende de rêve . Ils sont conçus pour y do coiffure oppleve un grand, avec des résultats étonnants merkbart. Nous consacrons-nous ici å servir chaque client avec lisseur ghd produit beste et Best service.and ces ghd droit Rod Price mer tiltrekke you.We pense que vous nageoire vos lisseur ghd pas cher de favoris.

    Reply
  • Fake Oakley Women fast delivery

    Posted by wyxaexedz on 06/29/2013 08:10pm

    ray ban outlet ,Oakley sunglasses made to change yearly, just like another style?? However, your options are extremely different game situations, there is absolutely no truly fashion. Oakley sunglasses, black frame clear lens for affordable Oakley sunglasses design in Asia a lot more than other ways is a good example. Replica Oakley Sunglasses ,Its massive amount good-looking, because it's well-made, they are effortless to performance technology and fashion combining. Supporting the lens with Oakley, you can always think the best. You should expect how the optical performance from Oakley. First, the lenses with Oakley Hydrophobic? / Oleophobic technology, high-performance coatings, water slide out, to keep how well you see clear, as well as overcome the stain from skin oils and lotions. Fake Oakley Radar ,Simple and easy generous, discount Oakley sunglasses, and very soon all brands have taken the importance, has additionally become fashionable for decades been popular "better product". Sunglasses every number of kind of one particular color, even though the ancient sunglasses brand 's all set, even so the eyes of the first factor. Can make many different colors and shapes, making sure that women are beautiful, on the fashion and also the hottest sunglasses, new sunglasses released a different women's styles trendy. Especially frame by specialized type O substance material, that's closely flexibility and production, to absorb the impact. This particular function, relaxed portions of Oakley sunglasses. Since there are a huge number of types of glasses, that you are guaranteed to certainly be a little thing, and relates to any person's spouse and youngsters. An advanced person engaged therein adventure sports or any sports, you can aquire cheap for being protected in order that you Oakley sunglasses, they may be very well liked. The integration of science and art Oakley won a lot more than 600 patents worldwide. Today, Jannard's brand has turned into a prominent symbol of success. On the top-selling sunglasses among manufacturers towards the market today, you could are located in the entire looking for a gorgeous sunglasses fashion a distinctive lady. Clothing, including different materials, that's pleasant and cozy complexion. In addition to this, women's clothing can be obtained from different colors, patterns and standards of measurement. Oakley sunglasses are sometimes placed on the usage of tools for instance drills or saws, adverse to avoid skyrocketing debris on the eye area. Many different types of Oakley sunglasses, you can purchase a doctor's prescription goggles since the angle trouble.

    Reply
  • Para crear Celebrity Peinado con GHD

    Posted by wanzilucky on 06/05/2013 06:52pm

    [url=http://ghdchheapoutlet.moonfruit.com/]Planchas ghd[/url] El plancha de pelo puede ser liso e rizado, largo e corto. Mientras que muchas mujeres prefieren tener su estilo de pelo pure, a new otros l’ensemble des gusta tener n’t estilo diferente de vez durante cuando e eliminar algunas imperfecciones como el frizz y simply las ondas naturales. [url=http://www.planchasespanaghdtop.net/plancha-pelo-ghd/]baratas ghd outlet[/url] Gracias a Twitter, he descubierto que algunos de ustedes estaban dispuestos a descubrir cuál es la diferencia entre el Cloud Nine y el ghd IV Styler fueron – y si valía la pena cambiar de lealtades o actualizar desde una alternativa más barata. Así que he creado esta tabla de comparación rápida que espero que le ayuda a tomar una decisión.Las mujeres han luchado por conseguir la perfección salón de golpe el cabello secado en su casa durante años. Mi cabello es grueso y recto, naturalmente, así que he estado en la búsqueda de un secador de pelo increíble que es bastante, pero se seca el pelo rápidamente y me da un poco de volumen. [url=http://comprarsaleghd.webstarts.com/]planchas ghd baratas[/url] Una función adicional sorprendente de la styler ghd es, en realidad es automático de cierre después de media hora, asociado con la falta de uso. Olvídate de continua se preocupa que simplemente queda el metal real bloqueado dentro! El principal en una. platos sería la dimensión perfecta con respecto a diseñar fácilmente.Esto es cuando las cosas se ponen difíciles, porque si le gustaría hacer ritmos de rap, pero no tienen las herramientas, entonces su juego Por suerte, todavía hay algunos ritmo decente la fabricación de software por ahí que no proporcionan características maravillosas y muy precios razonables.

    Reply
  • Det er bedre enn Ã¥ kjøpe Monster Studio hodetelefoner

    Posted by mantouhmmm on 06/03/2013 07:08pm

    [url=http://www.monsternobeats.350.com/]beats by dre[/url] Dette rolig, beskyttelser utskiftbart hode sammen med smørbare hodebånd forsikrer bemerkelsesverdig letthet i mange år av sin tid sammen med en helt beskyttet sunt. Dette svingbare hodet kopper Bests ved hjelp av Dre Expedition gjør det mulig for sjekkliste å ha bare ett beregnet for røde sammen med den leverte saken sørger for rask bevegelse. Attributter forbundet med Bests ved hjelp av Dre Expedition En slags ytterste støy etterspørsel nivåer samt en overdreven bakgrunn forstyrrelse tilbakegang tilsier realisere dette hodetelefoner suksess muligens med øredøvende omstendigheter. [url=http://www.beatsstudionorge.weebly.com/]beats studio[/url] Dette rolig, beskyttelser utskiftbart hode sammen med smørbare hodebånd forsikrer bemerkelsesverdig letthet i mange år av sin tid sammen med en helt beskyttet sunt. Dette svingbare hodet kopper Bests ved hjelp av Dre Expedition gjør det mulig for sjekkliste å ha bare ett beregnet for røde sammen med den leverte saken sørger for rask bevegelse. Attributter forbundet med Bests ved hjelp av Dre Expedition En slags ytterste støy etterspørsel nivåer samt en overdreven bakgrunn forstyrrelse tilbakegang tilsier realisere dette hodetelefoner suksess muligens med øredøvende omstendigheter. [url=http://www.drebeatsnorge.qsite.dk/]beats by dre norge[/url] En av de viktigste funksjonene i denne musikken maker er den har gratis video tutorials som viser deg hvordan du bruker musikk maker programvare. Veiledningene vil veilede deg om vennlig brukergrensesnitt av programvaren. Vil du være godt på vei til å lage beats på et blunk. Det eneste som holder deg tilbake er deg, så la de kunstneriske ferdigheter kommer out.Dub Turbo vil hjelpe alle som er seriøse om å lage beats, eller for den personen som er bare ute etter noe å fordrive tiden. Hovedsakelig er det for omtrent alle som er interessert i å lage musikk.

    Reply
  • Pictures missing

    Posted by Rubem Nascimento da Rocha on 02/28/2013 01:29am

    The article's pictures are missing. I can't view them.

    Reply
  • Customize the confirmation window title

    Posted by Sam on 12/19/2012 09:11am

    Hello Bipin. Thanks for your useful post. Do you know any way to change the title of the confirmation window so it mentions something different than "The page at says:" ? Thanks Sam

    Reply
  • Appreciation

    Posted by Morteza on 04/16/2012 08:26am

    Awesome as always! Thanks

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds