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

I need to use JavaScript to create HTML to PDF and then upload the PDF file to a SharePoint Document Library

Our current project requires us to convert HTML to PDF and save it in a SharePoint Document Library. While we have successfully converted the HTML to PDF using Kendo plugin, we are facing challenges with storing it in SharePoint. It's worth noting th ...

Divide the canvas into 100 separate sections using Javascript

Help! I'm trying to divide a canvas into 100 squares that are 50x50px each, but my current code is becoming too lengthy with multiple for loops. Is there a more efficient way to achieve this with just one for loop? Below is the existing code snippet: ...

A DropdownListFor with a predefined value using ng-model

I am currently working on creating a DropdownList using the code snippet below. However, I am facing an issue where the default text "Select Product/Program..." is not being set in the dropdown. Strangely, when I remove the ng-model, it works correctly. Do ...

Reorder the Polymer dom-repeat element following a modification in the child component's value

My Polymer dom-repeat list is working fine on the initial value sorting for the children. However, when I update a value within a child element, the sort order of the list does not reflect the changes. What is the best way to achieve this? <body> ...

Dealing with React Native text overflowing beyond the screen width when using FlexWrap

I'm currently working on implementing a component in react native that consists of a row containing and components, but I'm struggling to achieve the desired outcome. Here's my current code: <View style={{ flexDirection: ...

Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet: let count = 0; function onLoad(){ count++ console.log(count); return new Promise((resolve) => { ...

Using dynamic imports in Next.js allows us to efficiently load modules based on variables defining the path

When utilizing dynamic import in Next.js, I am encountering an issue. The component renders successfully when the path is used directly, but fails to render when the path is accessed from a variable. const faq = dynamic(() => import('../faq/faq&apo ...

Enhance your checkbox and radio components with React Higher Order Components (H

I'm in the process of designing my own custom checkbox and radio components to ensure reusability. This is what I have so far: import React, { Component } from 'react' export class Checkbox extends Component { render() { return ...

Troubleshooting 404 AJAX Error in ASP.NET Core and Visual Studio 2022

I have been struggling for hours trying to make Ajax work, even after looking at numerous examples. I just can't seem to get it right. Below is a snapshot of my layout. I am using Visual Studio 2022 along with ASP.NET Core. Calling all experts - wha ...

Retrieve an array of existing fields in MongoDB by comparing a collection with an array of objects

I'm a newbie when it comes to Mongo and I'm attempting to compare an array with a collection of documents, returning a list of matching records. Let me break it down:First Array I have a collection (user) with the following documents: > db. ...

beforeprinting() and afterprinting() function counterparts for non-IE browsers

Is there a way to send information back to my database when a user prints a specific webpage, without relying on browser-specific functions like onbeforeprint() and onafterprint()? I'm open to using any combination of technologies (PHP, MySQL, JavaScr ...

The transmission of data from the server to the client is experiencing technical difficulties

In my meanjs application, I am trying to pass the last inserted ID from the server side using express to the client side in angularjs. Although the ID is properly returned on the server side, when accessed on the client side, it appears differently. For e ...

Issue with express-http-proxy where relative URL paths are not functioning as expected

My server is hosting an app along with a few simple web microservices. I want to access these services over the internet without having to open individual ports for each one. To achieve this, I decided to set up a reverse proxy on the server using express- ...

What is the best way to extract a value from two different HTML identifiers?

Something tells me that this task is quite simple. I just need some guidance on what I might be missing here. All I really want is a basic program that can extract the content from <span id "text"> and paste it into <div id="text2">. funct ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

Is there a way to confirm that a file has been chosen for uploading prior to form submission, by utilizing the jquery validator?

I have a section on my website where users can upload files. I am trying to implement validation to ensure that a file has been selected before the form is submitted. Currently, I am using the jQuery form validator plugin for handling form validations. Th ...

Is it possible to send an ajax request to a user control file with the extension .ascx?

I am trying to interact with a user control on my page through ajax. Is it possible to make an ajax request directly to the user control (.ascx) instead of .aspx or .ashx files? ...

As you scroll, this smooth marquee effect gently shimmers with each movement

I've been trying out this code to create a scrolling marquee text, but the issue is that after 7000 milliseconds it starts to jitter, which doesn't make the text look good. Any suggestions on how I can fix this problem? Let me know! <script ...

Limiting the combinations of types in TypeScript

I have a dilemma: type TypeLetter = "TypeA" | "TypeB" type TypeNumber = "Type1" | "Type2" I am trying to restrict the combinations of values from these types. Only "TypeA" and "Type1" can be paired together, and only "TypeB" and "Type2" can be paired tog ...