Transmit information back to ASP.NET using AngularJS

As a newcomer to coding, I have a question. I am retrieving data from my database using C# and AngularJS, modifying it, and then sending it back. Eventually, I will need to save the modified data in the database. Here is my code, thank you in advance. The code is written in Spanish.

var datosActuales = { 
    'id': $scope.datosActualizados.id,
    'remitente': $scope.datosActualizados.remitente,
    'proveedor': $scope.datosActualizados.proveedor,
    'destinatario': $scope.datosActualizados.correoDestinatario,
    'copia': $scope.datosActualizados.copia,
    'mensaje': $scope.datosActualizados.mensaje
};

$http.post('http://localhost:65110/api/CorreosProveedor/CorreoActual', datosActuales)
.then(function (response) {
    console.log(response);
}, function (response) {
    console.log("error..");
});
// POST api/<controller>
[HttpPost]
public void CorreoActual(int id, string remitente, string proveedor, string destinatario, string mensaje, string copia)
{
    try
    {
        //string separa_copias = copia.Split(new char[] { ',' });
        ModeloCorreo correo_recibido = new ModeloCorreo();

        correo_recibido.id = id;
        correo_recibido.remitente = remitente;
        correo_recibido.nombre_proveedor = proveedor;
        correo_recibido.destinatario = destinatario;
        correo_recibido.mensaje = mensaje;
        // correo_recibido.correos_copia = separa_copias;
    }
    catch (Exception ex)
    {

    }
}

The error message displayed in the console is:

405 Method not allowed

Answer №1

Check out the following code snippet:

$http({
    method: "POST",
    url: 'http://localhost:65110/api/CorreosProveedor/CorreoActual' 

    }).then(function successCallback(response) {
            console.log(response);
    }, function errorCallback(response) {
    console.log("error..");
    });

If you have any questions or need further assistance, feel free to leave a comment!

Answer №2

My code is now complete and functioning perfectly.

After receiving a response from my database, I make necessary edits and send it back. ASP.NET then processes the response to determine if any updates, deletions, or insertions are required.

Thank you for your assistance.

        [Route("api/configuracorreo")]
        public void Post([FromBody]ModeloEditarCorreo correo)
        {
            try
            {

                ModeloEditarCorreo received_email = email;

                received_email.id = email.id;
                received_email.sender = email.sender;
                received_email.provider_name = email.provider_name;
                received_email.recipient = email.recipient;
                received_email.message = email.message;
                received_email.cc_emails = email.cc_emails;


                using (Certificados_UVM_DEVEntities dba = new Certificados_UVM_DEVEntities())
                {

                    Models.Email_Config existing_email = dba.Email_Config.FirstOrDefault();


                    if (existing_email == null)
                    {
                        string insertEmail = string.Format("INSERT INTO Email_Config (sender, provider_name, recipient, message) VALUES ('{0}', '{1}', '{2}', '{3}')", email.sender, email.provider_name, email.recipient, email.message);
                        dba.Database.ExecuteSqlCommand(insertEmail);


                        foreach (string cc_email in email.cc_emails)
                        {
                            Models.Email_Config created_email = dba.Email_Config.FirstOrDefault();
                            string insertCcEmails = string.Format("Insert INTO Email_Config_Cc (email_config_id, cc_email) VALUES ('{0}', '{1}')", '1', created_email.id);
                            dba.Database.ExecuteSqlCommand(insertCcEmails);
                        }

                    } else
                    {

                        string updateQueryString = string.Format("UPDATE Email_Config SET provider_name = '{0}', recipient = '{1}', message = '{2}' WHERE id = '{3}'", email.provider_name, email.recipient, email.message, email.id);
                        dba.Database.ExecuteSqlCommand(updateQueryStoreString);

                        string deleteCcEmails = string.Format("DELETE FROM Email_Config_Cc WHERE email_config_id = '{0}'", email.id);
                        dba.Database.ExecuteSqlCommand(deleteCcEmails);

                        foreach( string cc_email in email.cc_emails)
                        {
                            string insertCcEmails = string.Format("Insert INTO Email_Config_Cc (email_config_id, cc_email) VALUES ('{0}', '{1}')", email.id, cc_email);
                            dba.Database.ExecuteSqlCommand(insertCcEmails);
                        }

                    }




                }
            }


            catch (Exception ex)
            {

            }

        }
        
        
         public class ModeloEditarCorreo
    {
        public int id { get; set; }
        public string sender { get; set; }

        public string provider_name { get; set; }

        public string recipient { get; set; }

        public string message { get; set; }
        public string[] cc_emails { get; set; }


    }

$http.get(DIR.hostSelected + 'api/emailconfiguration').
then(function(response) {


var emails = response.data.cc_emails.map(function(e){
return e["cc_email"];
});
var cc_emails = emails.join(", ");

$scope.isSenderDisabled = response.data.sender ? true : false;

$scope.originalData = {
id: response.data.id,
sender: response.data.sender,
provider: response.data.provider_name,
recipientEmail: response.data.recipient,
cc: cc_emails,
message: response.data.message
};

});


$scope.validateEmail = function() {
if ($scope.recipientEmail != $scope.confirmEmail) {
$scope.IsMatch=true;
return false;
}
$scope.IsMatch=false;
};

$scope.cancel = function() {
$window.location.reload();
};


$scope.updateData = function(){

var currentCC = [];
currentCC = $scope.originalData.cc.split(", ");

$scope.editData = {};
$scope.editData = angular.copy($scope.originalData);
$scope.updatedData = $scope.editData;
var currentData = {
'id': $scope.updatedData.id,
'sender': $scope.updatedData.sender,
'provider_name': $scope.updatedData.provider,
'recipient': $scope.updatedData.recipientEmail,
'cc_emails': currentCC,
'message': $scope.updatedData.message
};
$scope.isDisabled = true;

console.log($scope.updatedData);
console.log(currentCC)

var config = { headers: {'Content-Type': 'application/json;charset=utf-8'}}

$http.post(DIR.hostSelected + 'api/emailconfig', currentData, config)
.then(function (response) {
console.log(response);
}, function (response) {
console.log("error..");
});

};

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

Record numerous button clicks in the database

Currently, I am developing a web application designed for parents to care for their newborns. Within the app, there are three buttons allocated for each task forming a progress flow, which indicates the completion status of each task (for example, steps fo ...

`Discover the latest version of Tailwind using JavaScript or PHP`

My setup includes Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30, and Tailwind https://i.sstatic.net/fVbJB.png I am looking to fetch the Tailwind version in JavaScript similar to how I can get the Vue version using: //app.js require('./bootstrap'); ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Modify the indicator color of the tabs in Material UI v5

https://i.sstatic.net/nhXHL.png I have implemented tabs in my project, but I am unable to change the background indicator: const theme = createTheme({ MuiTabs: { root: { styleOverrides: { indicator: {backgroundColor: "red !i ...

Choosing CSS/JS selector: Pick the final element with a class that does not match

My goal is to extract the most recent td element from the latest tr within an HTML table, ensuring that the latest td does not belong to the disabled class. I am attempting to achieve this using pure JavaScript with CSS selectors (without relying on jQuer ...

Unable to retrieve any data while consuming a RESTful web service with AngularJS

As a novice in Angularjs, I am seeking assistance with examples for the following: The added script is as follows: var app = angular.module('myapp', []); app.controller('MyCtrl1', ['$scope', 'UserFactory', functio ...

Capturing a res.send(404) error in ExpressJS during production: Tips and tricks

Can middleware handle errors like 404 and 500 when they are returned this way? exports.index = function(req, res) { res.send(404); } In production, I would want to display a custom missing page for these errors. However, my error handler middleware doe ...

The error message "mapboxgl is not defined" indicates that the mapboxgl variable

I have been encountering the following error message in the console, and despite spending hours trying to troubleshoot it, I have been unsuccessful in resolving the issue. Could someone assist me in fixing this problem? error image I am having difficulty ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

Steps for creating a herringbone design on an HTML canvas

Seeking Help to Create Herringbone Pattern Filled with Images on Canvas I am a beginner in canvas 2d drawing and need assistance with drawing mixed tiles in a cross pattern (Herringbone). var canvas = this.__canvas = new fabric.Canvas('canvas' ...

Execute Jest tests exclusively on the directory you are currently in

When I run Jest on my machine by typing jest from the terminal, it automatically executes tests from parent folders as well. However, I want to only run tests from the current folder. For example, if I navigate to c:/dev/app in the terminal and enter a co ...

Node JS fails to return body content in POST request

Exploring Node JS for the first time and attempting to post data to a specific URL and retrieve it. Using Postman for this task, but encountering an issue where the response data is coming back as undefined despite receiving a 200 status code. Even after ...

Submitting a Form with Multiple Pages

I'm encountering a challenge that I'm struggling to work through. Initially, we had a professional build our website, but since parting ways with the company, I've taken over site management. While I can handle basic tasks, I lack the expert ...

Disable the default controls on the Open Layers Bing Map

I am currently working on an App that utilizes Geolocation with Open Layers to load a Bing Map Layer. My goal is to enable touch-based zooming and remove the default zoom buttons. Additionally, I would like to relocate the 'i' button to prevent a ...

Cookie-powered JavaScript timer ceases after 60 seconds

I'm having an issue with my countdown timer where it stops counting after just one minute. It seems to pause at 54:00 when I set it for 55 minutes, and at 1:00 when I set it for 2 minutes. Any suggestions on how I can resolve this and make it continue ...

Tips for creating ui-sref links by using a mix of translate and ng-bind-html

I'm having trouble figuring out how to create a functional ui-sref link from a translated string. Using angular 1.4.9 along with angular translate 2.9.0 Below is the relevant code snippet <div ng-bind-html="$scope.getTranslatedText(someObject)"& ...

Looking to change the font text color in the filter section of the react-data-table-component-extensions?

Can anyone offer some assistance with this issue? I am currently using react-data-table-component along with react-data-table-component-extensions. I have also imported the index.css for the component-extension. import DataTable from "react-data-tabl ...

Record every function within the array prototype

Exploring methods that can be accessed on an array object: > console.log(Array.prototype) [] undefined > console.log(Array.prototype.push) [Function: push] Is there a way to view or log all properties/methods accessible on an object's prototyp ...

Press the option "Switch to red button" in order to transform the text color to red, and then revert back to its initial color

I am trying to implement a feature where the "convert to red button" changes the text to red in the preview paragraph, and then reverts back to the primary color according to the theme - black in the light theme, white in the blue and black background them ...

What factors influence the speed of an Ajax request?

It is common knowledge that the amount of data transmitted to the server, as well as the volume of information returned in a call can greatly affect its speed. However, what I am curious about is whether the following factors might also impact the transmi ...