Removing a specific row in a database table and sending a boolean indicator to an API, all while keeping the original object intact

I'm currently working on a spa project using AngularJS and integrating an api with mvvm in C#.

One issue I am facing is that when I click the delete button, it deletes the line but I only want to change a boolean flag to true on the server side while keeping the data in my Sql Server.

I experimented with different methods, including deleting the object through Postman, but my goal is not deletion; rather, I want to update a boolean property for the record that is no longer visible in the view table.

Below, you'll find my code for better clarity:

Any assistance or suggestions would be greatly appreciated.

 <tbody>
                <tr ng-repeat="register in registers">
                    <td style="display:none">{{register.UserId}}</td>
                    <td>{{register.Name}}</td>
                    <td>{{register.LastName}}</td>
                    <td><input type="checkbox" ng-model="register.IsActive" disabled /></td>
                    <td>{{register.Email}}</td>
                    <td>
                        <a ng-click="editRegister($event, register)" class="glyphicon glyphicon-edit"></a>
                    </td>
                    <td>
                        <a href="" ng-click="deleteRegister()" class="glyphicon glyphicon-trash"></a>
                    </td>
                </tr>
            </tbody>

My controller.js:

 $scope.deleteRegister = function (register) {
    var index = -1;
    var listOfRegister = eval($scope.registers);
    for (var i = 0; i < listOfRegister.length; i++) {
        if (listOfRegister[i].register === register) {
            index = i;
            break;
        }
    }
    if (index === -1) {
        alert("Something gone wrong");
    }
    $scope.registers.splice(index, 1);
    $http({
        method: 'Delete',
        url: 'http://localhost:51734/api/UserAPI/',

    }).then(function (res) {
        alert('Exc');
        $scope.GetAllRegisters();
    })
};

And My controller.api:

[HttpPut]
    [Route("api/UserAPI")]
    public HttpResponseMessage Delete(UserViewModel uservm)
    {
        try
        {                                
            var registerDeleted = ctx.User.Find(uservm.UserId);
            uservm.IsDelete = false;
            uservm.IsActive = true;
            if (registerDeleted != null)
            {
                uservm.IsActive = false;
                uservm.IsDelete = true;
                registerDeleted.Name = uservm.Name;
                registerDeleted.LastName = uservm.LastName;
                registerDeleted.IsActive = uservm.IsActive;
                registerDeleted.Email = uservm.Email;
                registerDeleted.IsDelete = uservm.IsDelete;
                ctx.Entry(registerDeleted).State = System.Data.Entity.EntityState.Modified;

                ctx.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User not found");
            }
        }
        catch (Exception ex)
        {

            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }

    }

Thank you!

Answer №1

What we are discussing here is the concept of soft deleting data entries. In your database, consider adding a new boolean field named Status or IsDeleted (or any other suitable name) with a default value of false. When you click on the Delete button in the user interface, simply update this flag from false to true.

When fetching the list of items to display on the UI, only include those where the flag is set to false.

This practice essentially involves marking data as deleted without actually removing it from the system.

Additionally, you can implement a process to move softly deleted data to an archived table for organizational purposes. This method allows you to easily restore deleted data by changing the flag back to false.

It's worth noting that when soft deleting an item, you only need to pass the record's ID. You typically wouldn't modify other fields while deleting. Below is a simple example of a controller function:

[HttpPut]
    [Route("api/UserAPI")]
    public HttpResponseMessage Delete(int userId)
    {                                       
         var foundUser = ctx.User.Find(userId);
         foundUser.IsDeleted = true;
         ctx.SaveChanges();
    }

Remember to handle validation and return codes accordingly. Also, update the method that retrieves active users to filter out those where the IsDeleted flag is true.

Answer №2

When dealing with issues related to the API, make sure to set uservm.IsDelete = false; and then set

registerDeleted.IsDelete = uservm.IsDelete;
. This will ensure that the value in the database is always false.

If you suspect that the template is causing the problem, consider extracting the index from the data-ng-repeat. Simplifying your code in this way can help clarify what is happening.

To remove a row from a table:

<tr data-ng-repeat="(index, register) in registers">    
     <td>
       <a href="data-ng-click="deleteRegister()" class="glyphicon glyphicon-trash"></a>
    </td>
</tr>      

$scope.deleteRegister = function (index) {
   $scope.registers.splice(index, 1);
}

Additional tip:

If you need to update an object, retrieve it first, make the necessary changes, and save it back.

var registerDeleted = ctx.User.Find(uservm.UserId);
if (registerDeleted != null)
{
    registerDeleted.IsDelete = true;
    registerDeleted.IsActive = false
    ctx.SaveChanges();
}

Answer №3

After mastering the technique of deleting a record from View.index using splice in my controller.js, I encountered a new challenge.

$scope.deleteRegister = function (index) {

    $scope.registers.splice(index, 1);
    $http({
        method: 'PUT',
        url: 'http://localhost:51734/api/UserAPI/',
    }).then(function (res) {
        alert('Exc');
        $scope.GetAllRegisters();
    })

};

Now, I am unable to establish communication with my method in controller.api to update the flag to isDelete = true after clicking the delete button on the UI.

This is a snippet of my controller.api:

//DELETE: api/UserAPI/5
    [HttpPut]
    [Route("api/UserAPI")]
    public HttpResponseMessage Delete(int userId)
    {
        try
        {
            var foundUser = ctx.User.Find(userId);

            if (foundUser != null)
            {
                foundUser.IsDelete = true;
                ctx.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK);
            }
}

And in my view.index:

<tr ng-repeat="(index, register) in registers">
    <td>
        <a href="" ng-click="deleteRegister()" class="glyphicon glyphicon-trash"></a>
    </td>
</tr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

Place the child DIV at the bottom of its parent DIV

I've searched through open questions but couldn't find a solution. The code snippet in question looks like this: ... <div style="some height"> <div style="some width"> .......and so on.. .. < ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

The Functionality of $rootScope.$broadcast with Dual Arguments

I've been reading through this interesting article: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec#.rlvow9x66 In an attempt to adapt their AuthInterceptor, I made modifications to handle ...

Exploring the TLS configuration for a Node.js FTP server project: ftp-srv package

I'm seeking to comprehend the accurate setup of TLS for my FTP project (typescript, nodejs) using this API: ftp-srv The documentation provided is quite basic. In one of the related github issues of the project, the author references his source code / ...

What is the best way to submit a Redux Form only if there have been changes made to any of the fields

I'm currently using Redux Form version 7.1.2, and I have a form that submits data when the user clicks the submit button. In the function assigned to handle the submission, I perform an action. However, I only want this action to be executed if there ...

Resetting suggestions for autocompletion in AngularJS

Currently implementing angularJS with autocomplete-alt. The functionality is working smoothly, but I've encountered an issue when clearing the autocomplete input using an AngularJS function - the suggestion list does not update accordingly. How can I ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...

Hey there! I'm currently facing some difficulties with storing form input data into a nested json file

I have developed a Next.js application with a form component structured as follows: components/Form.js import { useState } from 'react' import { useRouter } from 'next/router' import { mutate } from 'swr' const Form = ({ for ...

Vuetify offers a convenient solution for implementing multiple buttons in a Vue

My search bar retrieves data from an API query in the following format: Data: [[id, datafield1, datafield2],[id, datafield1, datafield2],...] I wish to include an on/off button for each row of the data, with each button having its own independent state. ...

Can you show me the method to retrieve the value of client.query in Node JS using PG?

I have been working with node.js to establish a database connection with postgresql. Here is what my dbConfig.js file looks like: var pg = require('pg'); var client = new pg.Client({ host:'myhoost', port:'5432', ...

What is the best way to show nested labels on separate lines simultaneously?

Despite attempting to utilize the map method as suggested in my research, it appears that it may not be suitable for the structure I am working with: const stepLabels = [ { labels1: ['First One'] }, { labels2: ['Second One', 's ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

Creating a jquery DataTable from HTML generated by angular $sce can be done by following these steps

I have created an Angular controller that takes data and generates an HTML table from it. The generated table is being displayed on the page. Now, I want to apply jQuery data tables using that scope variable. The variable contains the HTML code of the tabl ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

"Utilizing ng class with an array of objects: A step-by-step guide

I am facing a scenario in which my response appears as follows: "currency" : [ { "_id" : ObjectId("584aad5d3e2537613e5f4c39"), "name" : "USD" } ], I need to enable my checkbox based on the currency name. I attempted the followi ...

How can we display the data returned by a successful AJAX request

Having an issue with displaying Ajax success data. success: function(data){ alert(need to print it here); } When I try to access the data using: console.log(data.responseText); {"success":false,"errors":{"text":["Some text.","some more text"]}} Any ...

Using Javascript to read a JSON string displayed in a URL

I'm working on developing a straightforward web application that extracts latitude and longitude data stored in a JSON format and places markers on a Google map based on this information. Currently, there is a program running on a server that generate ...