The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database.

Javascript Function

function changeDepartment() {

    // Initializing and assigning variables
    var id = $('#requestId').val();
    var user = $('#contactUser').val();
    // Binding variables to data object
    var data = { id: id }
    // Making Ajax call with data.
    $.ajax({
        url: '@Url.Action("changeDepartmentActionResult", "ManageRequestResearch")',
        type: "POST",
        dataType: 'json',
        data: data,
        success: function (data, textStatus, XmlHttpRequest) {

            var name = data.name;

            window.location.href = '@Url.Action("Index", "ManageRequestResearch")';
            $('#btn-input').val('');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("responseText: " + jqXHR.responseText);
        }
    });
alert(data);

Furthermore, there is the action result:

[HttpPost]
public ActionResult changeDepartmentActionResult(string id)
{
    var moadEntities = new MOADEntities();
    moadEntities.Configuration.AutoDetectChangesEnabled = false;
    var researchBusiness = new ResearchRequestBusiness(moadEntities);
    var request = researchBusiness.FetchRequestById(Convert.ToInt32(id));

    var directoryObject = GetActiveDirectoryObject(request.Requestor);
    var requstorDisplayName = directoryObject != null ? directoryObject.DisplayName : request.RequestorFullName;
    var researchRequestFileBusiness = new ResearchRequestFilesBusiness(moadEntities);
    var requestFiles = researchRequestFileBusiness.FetchFilesByRequestId(Convert.ToInt32(id));

    var viewModel = new ManageSelectedRequestResearchViewModel()
    {
        RequestDetails = request,
        RequestActivity = request.tbl_ResearchRequestActivity.Select(d => d).ToList(),
        Files = requestFiles
    };

    moadEntities.Configuration.AutoDetectChangesEnabled = false;


    if (request.GovernmentEnrollment == true)
    {
        request.GovernmentEnrollment = false;
        request.ManagedCare = true;
        moadEntities.SaveChanges();
    }
    else
    {
        request.ManagedCare = false;
        request.GovernmentEnrollment = true;
        moadEntities.SaveChanges();
    }

    return Json("Status changed successfully", JsonRequestBehavior.AllowGet);
}

Upon observation, it seems to correctly handle the record, make changes accordingly, and even reach Context.SaveChanges() while debugging -- prior to saving changes, values show as updated, however, no changes are reflected in the database.

Moreover, I have verified the validity of connection strings.

Any insights on what might be causing this issue? Thank you in advance!

Answer №1

It appears that changes are being made to an entity without the auto-detect feature enabled.

If this is intentional, make sure to notify the context that the entity has been modified.

Assuming that MOADEntities is a subclass of DbContext, consider replacing the following code:

if (request.GovernmentEnrollment == true)
{
    request.GovernmentEnrollment = false;
    request.ManagedCare = true;
    moadEntities.SaveChanges();
}
else
{
    request.ManagedCare = false;
    request.GovernmentEnrollment = true;
    moadEntities.SaveChanges();
}

With this alternative approach:

// Simplify the if..else block
request.ManagedCare = request.GovernmentEnrollment;
request.GovernmentEnrollment = !request.GovernmentEnrollment;

// Notify the context that the 'request' entity has been modified.
// EntityState enum is located in the System.Data.Entity namespace
moadEntities.Entry(request).State = EntityState.Modified;

// Save the changes
moadEntities.SaveChanges();

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

Encountering the Extjs 3.4 error ERR_UNKNOWN_URL_SCHEME while trying to access a legitimate JSON

Using Extjs 3.4, I am working on a simple ajax request: Ext.Ajax.request({ url: "localhost:3000/offers.json", success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); }, failure: funct ...

Turning a Two Dimensional Object or Associate Array into a Three Dimensional Object using Javascript

Is there a method to transform the following: var stateDat = { ME: ['Maine',1328361], etc. }; Into this structure dynamically within a function? var stateDatHistory = { 1:[ ME: ['Maine',1328361], etc. ], 2:[ ME: ['Maine& ...

Choosing a Query with Puppeteer - Unleashing the Power of Selection in Puppeteer

How do I use Puppeteer to select the html anchor element that clicks and navigates to the Tutorial page? https://i.sstatic.net/6rkNn.png I've tried this but it's not working const puppeteer = require('puppeteer'); const url = process ...

Storing data from a form by utilizing AJAX with PHP

Is there a way to save the form data either in a file or a local database using AJAX, while still sending the data through the form action to an external database? If you want to view the source code for my form, you can find it here: http://jsbin.com/ojU ...

Encountering the 'unsupported_grant_type' error while attempting to retrieve an access token from the Discord API

Having trouble implementing Discord login on my website. When trying to exchange the code for an access token from https://discord.com/api/oauth2/token, I keep getting the error { error: 'unsupported_grant_type' }. This is my code: const ...

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

Node.js throwing error due to incorrect format of bind parameters as an array

I have been working with Nodejs/express and trying to implement a paramerized query in my API. However, I encountered the following error message in my console: Bind parameters must be array if namedPlaceholders parameter is not enabled Below is a snippet ...

What could be causing my ajax post function to malfunction when triggered by a button click event?

My attempts to send variables to a PHP file via AJAX when a button is clicked have been unsuccessful. Upon checking my PHP page, I noticed that the variables were not being received. $(document).ready(function(){ $("#qryBtn").click(function(){ ...

Struggled to Find a Solution for Code Alignment

Is there a tool or software that can align different types of codes with just one click? I've tried using the Code alignment plugin in Notepad++, but it hasn't been effective. For example, when aligning HTML code using tags, I couldn't find ...

Display the input text value when the button is clicked

I am a beginner in JavaScript and have created this HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> Upon entering text into the input field and clicking on the submi ...

Looping in REACT with state updates can cause the values to be overwritten

I'm encountering a problem with my function in React that updates the state. It fetches data from a URL in an array and creates a new item, but when trying to update another state array with this new object, it keeps overriding the first item each tim ...

Guidelines for Extracting TextBox Value from GridView

In my gridview, I have dynamically created TextBox controls in the RowDataBound event: TextBox txtbox = new TextBox(); txtbox.ID = "txt1"; txtControl.Text = "SomeValue"; However, when attempting to retrieve the value on a button click using the following ...

Establishing the folder organization for Express Handlebars

I work with NodeJs, Express, and Handlebars. The main file for my server is named app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); app.engine('handlebars', ex ...

The onClick event handler is executed during every rendering process

Initially, my default state is set as follows: this.state = { selectedTab : 'tab1' } When it comes to rendering, this is how I define it: render(){ const { selectedTab } = this.state; return( <li>tab1</li><li>ta ...

Step-by-step guide for launching a Next.js/Node application

Currently, I am developing a full-stack project utilizing a next.js application for the front-end and a node/express server for the API. The front-end and back-end are running on separate ports. Here is how my application is configured: https://i.stack.im ...

Troubleshooting: Issue with onclick event in vue.js/bootstrap - encountering error message "Variable updateDocument not found"

As a newcomer to frontend development, I have a basic understanding of HTML5, CSS, and Javascript. Recently, I started working on a vue.js project where I integrated bootstrap and axios. Everything seemed to be working fine until I encountered an issue whe ...

Tips for extracting a textfield input value and sending it using data-ajax-url="Url.Action() in a cshtml file

I have a challenge with my controller function that takes two dates as parameters. It works perfectly when I hardcode the dates, but I'm struggling to extract values from my text fields and pass them to the function. I prefer not to use a form in my c ...