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

Ways to collaborate on code among multiple projects

What is the most efficient way to share code between a React and Node.js application, both using vanilla JavaScript? Consider this snippet: function slugify(str) { return str.replace(/[^a-z0-9)(\.\-_\s]/gi, ""); } How can I implement t ...

Can anyone please guide me on how to extract the IP address of a specific individual using Node.js?

There's an individual running some kind of exploit scanner on my server. I'm receiving strange requests like: IP ADDRESS: ::ffff:127.0.0.1 www-0 (out): POST /cgi-bin/php5?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64 ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...

Issues with Ajax response being added to the table

I am encountering a technical problem with my university project. The task assigned by the professor is as follows: We need to create a static table that lists 3 domain names in order to enhance the performance of the domain availability API. <table&g ...

A guide to efficiently deleting multiple items using checkboxes and an Ajax request

Could someone assist me in deleting values with a checkbox using an AJAX call? I'm unable to identify the error. Also, this is a template and it already has a built-in "check all" feature so there's no need to modify any built-in code for the ch ...

How to Target a Specific Element Using its Class with jQuery

Hey there! I'm currently working with the following snippet of HTML code: <li class="grey"> <div class="row"> <button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button> </div ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

I'm looking for assistance on how to execute a render right after making a put or delete request

class ProductApp extends Component { constructor() { super(); this.state = { currentProduct: null, items: [], }; this.handleUpdateSubmit= this.handleUpdateSubmit.bind(this); } componentDidMount() { axios.get('h ...

Discovering the center of an element and implementing a left float

I'm looking for a way to dynamically position the element #ucp_arrow in the middle of a div using float: left. Here is an illustration: https://i.stack.imgur.com/nzvgb.png Currently, I have hard-coded it like this: JAVASCRIPT: $("#a_account").cli ...

Generate the URL based on the JSON feed

Can someone help me figure out what I'm doing wrong here? I'm attempting to create the image URL using the flickr.photos.search method now (I need to show images close to the visitor's geolocation), it was working with groups_pool.gne befor ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

Having trouble with the response function not functioning properly within an AJAX autocomplete

I have implemented an autocomplete feature using the jQuery UI plugin from http://jqueryui.com/autocomplete/#remote-jsonp. $("#city" ).autocomplete({ source: function( request, response ) { $.ajax({ url: 'index.php?secController= ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

ajaxStart event does not trigger when making an Ajax POST request

My ajaxStart event functions properly for ajax loads, but it does not work at all when I do a POST request. The following code is consistently rendered on all pages: $(document).ajaxComplete(function () { hideIcon(); if (stepState !== &a ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

What is the best way to scale down my entire webpage to 65%?

Everything looks great on my 1920x1080 monitor, but when I switch to a 1024x768 monitor, the content on my webpage becomes too large. I've been manually resizing with CTRL+Scroll to reduce it to 65%, which works fine. Is there a code solution using CS ...

Webpack2 now transforms sass/scss files into JavaScript rather than CSS during compilation

I've created a webpack script to compile all .scss files into one css file. I decided to use webpack instead of gulp or grunt for simplicity, as it can be configured in a single file. However, I am encountering an issue where scss files are being com ...

retrieve the complete webpage content, encompassing the .html file, images, .js files, css stylesheets, and more

I'm currently working on a project and could use some assistance. Is there a method available to download an entire page, including the .html file, images, .js files, css, etc., using PHP, JavaScript, or AJAX? <html> <body> & ...