Experiencing a problem with updating records in angular?

angular version: Angular CLI: 9.0.0-rc.7

I have encountered an issue while trying to update a record. After clicking on the edit icon, I am able to make changes to the record in the form. However, when I click on the Edit Button, the record gets updated in the browser console log but not in the database. Below is the code snippet from backendservice.ts:


       //when I click on edit icon then record going to form 

public editpartymaster(PartyMstId) {
        return new Promise(resolve => {
            let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
            let options = { headers: headers, crossDomain: true, withCredentials: true };

            var url = "http://localhost:000/PartyMsts/EditPatymaster?PartyMstId=" + PartyMstId;

             this.httpClient.post<any>(url, options).subscribe(
                (res) => {
                    console.log(res);
                    resolve(res);
                },
                (err) => console.log(err)
            );
        });
    }

    //edit button click event

    public editpartymasterid(PartyMstId, PartyCode, PartyName, Address, PhNo1, SDate, PartyDate, RDType, Exchange) {
        return new Promise(resolve => {
            let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
            let options = { headers: headers, crossDomain: true, withCredentials: true };

            var url = "http://localhost:000/PartyMsts/EditPatymaster";

            const postdata = {
                'PartyMstId': PartyMstId,
                'PartyCode': PartyCode,
                'PartyName': PartyName,
                'Address': Address,
                'PhNo1': PhNo1,
                'SDate': SDate,
                'PartyDate': PartyDate,
                'RDType': RDType,
                'Exchange': Exchange
            }

            console.log("formdata", postdata)

            return this.httpClient.post<any>(url, postdata)
                .subscribe((res) => {
                    console.log("res partyadd add 198", res);
                    resolve(res);
                });
        });
    }

Below is the code snippet from partymaster.component.ts:


    PartyMstId: any;
    PartyCode: any;
    PartyName: any;
    Address: any;
    PhNo1: any;
    SDate: any;
    PartyDate: any;
    RDType: any;
    Exchange: any;
    x: any;
    y: any;
    c: any;
    partylist: any;

   constructor(public myservice: BackendService) {}
//edit icon click event

onGridRowClicked(e: any) {
        if (e.event.target !== undefined) {
            let actionType = e.event.target.getAttribute("data-action-type");
            if (actionType == "edit") {
                console.log("e", e.data.PartyMstId);
                console.log("View edit action clicked");
                this.myservice.editpartymaster(e.data.PartyMstId).then((data: any) => {
                    if (data.message == "your record update") {

                        this.PartyMstId = e.data.PartyMstId;
                        this.PartyCode = e.data.PartyCode;
                        this.PartyName = e.data.PartyName;
                        this.Address = e.data.Address;
                        this.PhNo1 = e.data.PhNo1;
                        this.SDate = e.data.SDate;
                        this.PartyDate = e.data.PartyDate;
                        this.RDType = e.data.RDType;
                        this.Exchange = e.data.Exchange;
                    }
                });
            }
            else if (actionType == "delete") {
                console.log("View delete action clicked");
            }

//edit button click event
    editbuttonclickevent() {
        console.log("---PartyMstId---", this.PartyMstId);
        console.log("---PartyCode---", this.PartyCode);
        console.log("---PartyName---", this.PartyName);
        console.log("---Address---", this.Address);
        console.log("---PhNo1---", this.PhNo1);
        console.log("---SDate---", this.SDate);
        console.log("---PartyDate---", this.PartyDate);
        console.log("---RDType---", this.RDType);
        console.log("---Exchange---", this.Exchange);

        this.myservice.editpartymasterid(this.PartyMstId, this.PartyCode,
            this.PartyName, this.Address, this.PhNo1, this.SDate, this.PartyDate,
            this.RDType, this.Exchange).then((data: any) => {
            console.log("list data")
            if (data.message == "your record update") {
                this.list();
            }
        });
    }

In the provided ASP.NET MVC service code below, the issue seems to be related to updating the database after making changes to the record:

        public ActionResult EditPatymaster(int PartyMstId)
        {
            var partymst = poly.PartyMsts.Find(PartyMstId);
            partymstmodel partymstupdate = new partymstmodel();

            partymstupdate.PartyCode = partymst.PartyCode;
            partymstupdate.PartyName = partymst.PartyName;
            partymstupdate.Address = partymst.Address;
            partymstupdate.PhNo1 = partymst.PhNo1;
            partymstupdate.SDate = partymst.SDate;
            partymstupdate.PartyDate = partymst.PartyDate;
            partymstupdate.RDType = partymst.RDType;
            return View(partymstupdate);
        }

        [HttpPost]
        public JsonResult EditPatymaster(partymstmodel partymst, int PartyMstId)
        {
            var partymstupdate = poly.PartyMsts.Find(PartyMstId);

            if(partymstupdate!=null)
            {
                partymstupdate.PartyCode = partymst.PartyCode;
                partymstupdate.PartyName = partymst.PartyName;
                partymstupdate.Address = partymst.Address;
                partymstupdate.PhNo1 = partymst.PhNo1;
                partymstupdate.SDate = partymst.SDate;
                partymstupdate.PartyDate = partymst.PartyDate;
                partymstupdate.RDType = partymst.RDType;

                HttpResponseMessage response = staticvariable.client.PutAsJsonAsync("PartyMsts", partymst).Result;

                var data = new
                {
                    message = "your record update",
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = new
                {
                    message = "your record not updated",
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }

The issue described states that the console log shows the updated record, but the database does not reflect these changes. You can view the browser logs for more information:

https://i.sstatic.net/RDDG4.png

Although the console log displays the updated record, it appears that the database fields are not being updated as expected:

https://i.sstatic.net/RpxCJ.png

If you have any insights on how to resolve this issue, your help would be greatly appreciated. Thank you.

Answer №1

The error message in the console indicates that there is a CORS issue. Cross-Origin Resource Sharing (CORS) is a method that utilizes additional HTTP headers to allow web browsers to access resources from different origins. If you are utilizing ASP API as your backend, ensure to install the following NuGet packages:

Microsoft.AspNet.Cors

Microsoft.AspNet.WebApi.Cors

In your WebApiConfig class file, within the Register method, add the following line of code:

config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));

Answer №2

It is highly recommended to set up the asp.net cors package and configure it on your backend server. This involves enabling CORS as shown below:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, you need to activate CORS on your controller or specific method in the backend like this:

[EnableCors(origins: "*", headers: "*", methods: "*")]

Note that using origin * might not be the best approach for your situation. For more information on CORS, visit this link and customize it according to your needs.

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

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

Angular does not recognize the boolean variable

Within my Angular component, I have declared two boolean variables: editingPercent: boolean = true; editingCap: boolean = false; In the corresponding HTML file, there is a checkbox that updates these variables based on user input: checkedChanged(e) { ...

Upon receiving data from the Api, the data cannot be assigned to the appropriate datatype within the Angular Object

I am encountering an issue with the normal input fields on my page: https://i.stack.imgur.com/qigTr.png Whenever I click on the "+" button, it triggers an action which in turn calls a service class with simple JSON data. My intention is to set selectionC ...

Obtain the specific generic type that is employed to broaden the scope of a

I am working on a class that involves generics: abstract class Base<P extends SomeType = SomeType> { // ... } In addition, there is a subclass that inherits from it: class A extends Base<SomeTypeA> { // ... } I'm trying to figure out ...

Unable to modify the date input format in Angular when utilizing the input type date

I am currently working with angular 10 and bootstrap 4. I am trying to update the date format in an input field from (dd/mm/yyyy) to DD/MM/YYYY, but I am facing issues. Below is my angular code: <input type="date" id="controlKey" cl ...

What is the process to activate/deactivate a drop-down menu once a radio button has been chosen

JSON Data: radio1Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, { value: 'col-2', viewValue: 'Col-2' } ]; radio2Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, ...

Relocating the Asp.Net WebAPI to its own domain apart from the Asp.Net MVC site in preparation for the AngularJS

We currently have an Asp.Net MVC 5.0 project that utilizes AngularJS for the front end. The project includes a WebAPI Controller within the same project and is deployed on the same website. This application was created using the Individual User Account pro ...

The Angular2 project using ag-grid-enterprise is currently experiencing difficulties with implementing the License Key

I have a valid license for the ag-grid-enterprise version, but I'm struggling with how to integrate it into my Angular2 project. I've attempted placing the license in the main.ts file using LicenseManager and specifying the enterprise version in ...

Converting a C# Dictionary<string,string> to a TypeScript Map<string,string>

Struggling to find the best approach for handling key:value pairs in TypeScript when receiving a dictionary object from the C# backend. Everything attempted so far has not yielded the expected results. This is the C# code snippet: var displayFields = ...

Adding a class dynamically to a <span> based on the value of a field or property

Learning Angular is still new for me, so please be patient. I have a TagComponent that includes a Color-enum and one of those colors as a property. I want Angular to automatically assign this color as a class so that Semantic UI can style it accordingly. ...

Should we utilize the component @Input as a parameter for the injected service constructor, or should we opt for the ServiceFactory

Within Angular 12 lies a simplified component structured as follows: @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.less'] }) export class ListComponent implements ...

What is the best way to increase the size of an array and populate it with just one specific element in Types

If I want to create an array in Python, like [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], all I have to do is use [1] * 10. >>> [1] * 10 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Is it possible to achieve the same result in TypeScript? ...

Using TypeScript for Type Inference in Fetch Operations

I created a custom Fetch wrapper in Typescript to fetch data from my API. I am facing an issue where the retrieved data is of type "any" and I want to convert it to a specific type, like "user". Here is the link to my codesandbox for reference: https://co ...

Is there a way to modify the button exclusively within the div where it was pressed?

I plan to incorporate three buttons in my project (Download, Edit, and Upload). Upon clicking the Download button, a function is triggered, changing the button to Edit. Clicking the Edit button will then change it to Upload, and finally, clicking the Uplo ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. ...

Creating an online bidding platform using ASP.Net, MVC 5, and Entity Framework

Having recently delved into the world of ASP.NET, I am in the process of developing a basic auction site for a charitable cause. Utilizing MVC 5 and Entity Framework with Code-First approach for database management. The core of this project is the Item mo ...

Creating a loading screen in Angular2: Step-by-step guide

How can you best integrate a preloader in Angular 2? ...

Retrieve data from REST call to populate Material dropdown menu

I am looking to dynamically populate a dropdown menu with data retrieved from a Rest API. I attempted the following code: <Select id="country-helper"> {array.map((element) => ( <MenuItem value={element.code}>{element.country}& ...