Posting and deleting data in AngularJS using HTTP requests

Incorporating both angularjs and c# webapi in this situation.

My approach involves calling the webapi from angularjs and passing a json array.

Here is the Angularjs code snippet:

    factory.delete  = function (json) {
    var url = 'myUrl';
    return $http.post(url, json).then(function (res) {
        return res;
    }, function (err) {            
        throw err;
    });
   }

As for the C# Api:

  [HttpPost("data/delete")]
  public async Task<IActionResult> DeleteData([FromBody] List<UserEntity> 
  jsonData)
  {
     //Perform deletion logic here based on the json data
  }

I'm questioning if my method of using post instead of httpdelete for deleting is correct. So far, the above method works successfully

An attempt was made to use http delete as shown below:

 factory.delete  = function (ids) {
    var url = 'myUrl';
    return $http.delete(url, ids).then(function (res) {
        return res;
    }, function (err) {            
        throw err;
    });
   }

   [HttpDelete("data/{ids}/delete")]
    public async Task<IActionResult> DeleteData(string ids)
    {

       //Within this method, ids are expected to be comma separated and each ID will be deleted individually

    }

However, I am facing an issue with the ids parameter being null within the API. Any insights or suggestions would be greatly appreciated.

Answer №1

While this may not directly answer your question, it could assist you in troubleshooting the issue at hand. By incorporating the code snippet below into your API class, you can gain better insight into how JSON is converted to your parameters:

[HttpPost("data/delete")]
public async Task<IActionResult> DeleteData([FromBody] List<UserEntity> jsonData)
{
    if (!ModelState.IsValid)
    {
        var error = ModelState.Values
            .SelectMany(x => x.Errors)
            .FirstOrDefault(x => x.Exception != null);

        return BadRequest(error != null 
            ? error.Exception.Message
            : "Error in JSON request");
     }
     // Add your regular processing logic here
}

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

What are the placeholders for the "localIdentName" query tag in a custom CSS-loader for Webpack?

Just starting out with Webpack and experimenting with the css-loader. I came across the option to specify a localIdentName query tag on the Github page under "Local Scope". This tag allows us to define our own custom values for how classes should be named ...

Updating state array within reducer leads to duplicate execution of calculations

const updateCartReducer = (state, action)=>{ console.log('running the updater function') const existingItemIndex = state.items.findIndex( (item) => item.restaurant === action.item.restaurant && ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Unable to convert data from a string type to a custom object or model

My attempt to deserialize JSON data from an HTTP response into a specific Model is failing with the following exception: Message=Error converting value "{"Id":"1","UserName":"RK"}" to type 'ConsoleApp5 ...

Reactjs: Prop Type Error - Issue with retrieving the values from props during data submission

Currently, I am developing a social app where users can post screams, like posts, and add comments. The issue I'm encountering is that I am not receiving the props value when posting a new scream initially, but after refreshing the page, everything wo ...

The user values in jQuery alert function are correct, but the saveorupdate function fails to save null values in the database table

While using the alert function in jQuery, the user input values are alerted correctly, but for some reason they are being stored as null in the database table. Can anyone help me identify what might be causing this issue or what I might be doing wrong? I& ...

Dealing with complications in the Rails asset pipeline management

I am working on a webpage that requires real-time data to be displayed. Therefore, it necessitates continuous ajax communication post page load. similar to this, jQuery -> setInterval -> $.ajax url: "some url" success: (data, te ...

Is it possible to determine the total number of pages in a PDF using PDF.js in

Is there a way to retrieve the total page count using pdf.js? <script type="text/javascript"> $( document ).ready(function() { var pdf = pdfjs.getDocument('sample.pdf'); alert(pdf.numPages); }); </script> ...

Issues with the functionality of Google Translate's JavaScript code snippet are causing

After trying out the code snippet provided on w3schools.com, I encountered a discrepancy between the results displayed on the website and those on my personal computer. <div id="google_translate_element"></div> <script> function googleT ...

Issue encountered when attempting to add multiple JavaScript functions through Greasemonkey using unsafeWindow

One issue that arises is that the functions are unable to recognize each other. For example: unsafeWindow.helloworld = function() { alert('Hello world!'); helloworld2(); // this fails with an error indicating it does not exist } unsa ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Deactivate the button once it's been used | Discord.js version 14

In my index.js, I created a function to respond when a button is pressed and then disable it. client.on("interactionCreate", async (interaction) => { if (interaction.isButton()) { if (interaction.customId === "yes") { co ...

I am struggling to set a required input in Angular2

I am new to Angular and currently working on a project that requires input validation to ensure that no field is left blank. The project consists of an HTML file along with a .ts file for functionality. Below is a snippet from the HTML: <div class="f ...

Angular 2 component stays static despite changes in route parameters

So, I am in need of a way to refresh my component after the URL parameter's id has been altered. The following code is from my player.component.ts: import {Component, OnInit, AfterViewInit} from '@angular/core'; import {ActivatedRoute, Rout ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...

How to effectively navigate through HTML templates in directives?

Seeking a comprehensive reference for navigating the html used in a directive template. Does anyone have recommendations? While examining elem (via link:(scope, elem, attrs)) through console log, it appears there are additional functions and attributes be ...

Exploring the Integration of AngularJS with MVC Subdomains

We are looking to incorporate some AngularJS SPA features into our existing MVC 5 application. To achieve this, we have created a new MVC Area within the application and set up a default controller called HomeController. namespace Acme.WebAdmin.Areas.Sche ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

Discovering the position of elements in relation to their (grand^N)parent

Among my possessions are elements A and B. B has the ability to exist as a direct child of A, or there may be anywhere from 0 to N elements separating them. It is imperative that I determine how B is situated in relation to A, specifically noting the dist ...

having trouble launching ionic serve following the upgrade to Ionic 2

Recently, I've been revisiting an old Ionic v1 project after working with Ionic v2. However, when trying to run 'ionic serve' in the v1 project's root directory, I encountered the following message: Looks like a fresh checkout! No ./no ...