Leverage jscript and controller actions in MVC ASP.net to effectively insert new data into the database

I am looking to store data in a database from my MVC ASP.net project without the need to refresh the view page. My approach involves creating a string, sending it to the controller, and then pushing it to the database. I have already developed a function for string creation...

function CreateChain() {

        RecordID = document.getElementById("RecordIdTextBox").value
        RecordDate = document.getElementById("RecordDateEntry").value
        Employee = document.getElementById("EmployeeTextBox").value
        Department = document.getElementById("ddlDepartmentsOption").value
        SubDepartment = document.getElementById("ddlSubDepartments").value
        Machine = document.getElementById("ddlMachines").value
        Equipment = document.getElementById("ddlEquipment").value
        Problem = document.getElementById("InvisibleProblemsddl").value
        Grade = document.getElementById("Gradeddl").value
        GradeComment = document.getElementById("GradeComment").value
        WorkOrderStatus = document.getElementById("WorkOrderStatus").value
        WorkOrderNumber = document.getElementById("WorkOrderNumber").value

        chain = ("RecordID:" + RecordID + ',' +
            "RecordDate:"+ RecordDate + ',' +
            "Employee:"+ Employee + ',' +
            "DepartmentID:"+ Department + ',' +
            "SubDepartmentID:"+ SubDepartment + ',' +
            "MachineID:"+ Machine + ',' +
            "EquipmentID:"+ Equipment + ',' +
            "ProblemID:"+ Problem + ',' +
            "Grade:"+ Grade + ',' +
            "GradeComment:"+ GradeComment + ',' +
            "WorkOrderStatus:"+ WorkOrderStatus + ',' +
            "WorkOrderNumber:"+ WorkOrderNumber)
        console.log(chain);

    }

An example of the resulting string is as follows:

RecordID:5,RecordDate:2021-08-02T13:50:46,Employee:Josh,DepartmentID:1,SubDepartmentID:1,MachineID:16,EquipmentID:141,ProblemID:59,Grade:A,GradeComment:the machine is working,WorkOrderStatus:true,WorkOrderNumber:123456

To accomplish this task, I would like to know how to 1.) Transfer this string to the controller and 2.) Utilize the controller to integrate this into my database?

All the data points align with the table "RecordEntry" in my database and have been named accordingly.

EDIT: I have incorporated this function in the view now. However, when executed, it does not proceed beyond the alert(chain) statement. Do you have any insights into why this may be happening? The other commented-out alert does respond.

EDIT: It just dawned on me that there was no AJAX call within the function but I had placed it outside. Is it essential to include it within the function so that it gets invoked upon pressing a submit button?

    function CreateChain() {

        //alert("running function createchain");

        Record = document.getElementById("RecordIdTextBox").value
        RecordDate = document.getElementById("RecordDateEntry").value
        Employee = document.getElementById("EmployeeTextBox").value
        Department = document.getElementById("ddlDepartmentsOption").value
        SubDepartment = document.getElementById("ddlSubDepartments").value
        Machine = document.getElementById("ddlMachines").value
        Equipment = document.getElementById("ddlEquipment").value
        Problem = document.getElementById("InvisibleProblemsddl").value
        Grade = document.getElementById("Gradeddl").value
        GradeComment = document.getElementById("GradeComment").value
        WorkOrderStatus = document.getElementById("WorkOrderStatus").value
        WorkOrderNumber = document.getElementById("WorkOrderNumber").value

        return {
            "RecordID": Record,
            "RecordDate": RecordDate,
            "Employee": Employee,
            "DepartmentID": Department,
            "SubDepartmentID": SubDepartment,
            "MachineID": Machine,
            "EquipmentID": Equipment,
            "ProblemID": Problem,
            "Grade": Grade,
            "GradeComment": GradeComment,
            "WorkOrderStatus": WorkOrderStatus,
            "WorkOrderNumber": WorkOrderNumber
        };
    
        var chain = CreateChain();
        alert(chain);
        $.ajax({

            url: "/RecordEntries/AddtoDatabase",
            type: "POST",

            data: { model: chain },

            success: function (result) {
                alert("Success");
            },
            error: function (xhr, exception) {
                alert("Error");
            }
        });
    }

This is the submit (next) button used:

<a class="btn btn-success btn-block btn-lg " onclick="NextButtonClick()" id="nextbutton"><font color="white">Next</font></a>

Furthermore, here is the function called by the button which in turn triggers multiple other functions:

    function NextButtonClick() {

        HideSelectionsBeforeNextSelection();
        ShowDropDownsAgain();
        //removefromList();
        ResetValues();
        IncreaseRecordIdByOne();
        CreateChain();
    }

Answer №1

Give this a try!

JavaScript:

function CreateChain() {

        //alert("running function createchain");

      var  Record = document.getElementById("RecordIdTextBox").value;
       var  RecordDate = document.getElementById("RecordDateEntry").value;
        ........
var chain= {
            RecordID: Record,
            RecordDate: RecordDate,
           .....
        };
    

        alert( JSON.stringify( chain));
        $.ajax({

            url: "/mycontroller/myaction",
            type: "POST",

            data: { model: chain },

            success: function (result) {
                alert(result);
            },
            error: function (xhr, exception) {
                alert("Error");
            }
        });
    }

Server-side:

Create the ViewModel:

public class ChainViewModel
{
 public int RecordID {get; set;}
  public string  RecordDate {get; set;}
   public string  Employee {get;set;}
....and so on
}

Controller:

public class MyController :Controller
{

public ActionResult MyAction( ChainViewModel model)
{
    ....use model data to submit to db

    return Ok("Success");
}

}

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

Encountered an error when attempting to submit with Node.js and Express.js connected to MySql - "Cannot POST /login

I am currently working on creating a basic login page using node.js with the express.js and mysql packages. The goal is to redirect users to the layout.html page if their username and password exist in the mysql database. For this project, I have set up a ...

Capture every incoming request with various HTTP methods using nock

Check out the updated intercept function below: interceptWithError() { nock(baseUrl) .get(/.*/) .replyWithError(500); nock(baseUrl) .put(/.*/) .replyWithError(500); nock(baseUrl) .post(/.*/) .replyWithError(500); nock(ba ...

How come I'm getting a numerical output instead of an array after using the array.push() method in this code?

In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in ...

The medium-zoom feature is currently experiencing issues with functionality within Angular version 13

I've been attempting to incorporate medium-zoom functionality into my project using https://www.npmjs.com/package/medium-zoom Here are the steps I took: ng new medium_zoom_test (Angular 13) with routing & css npm install medium-zoom The image is ...

You can easily dismiss the modal by clicking on any part of the screen, not just the button

I have a problem with my current code where I can only close a modal by clicking on a specific button. I want to modify it so that the modal can be closed by clicking anywhere on the screen. Unfortunately, as a JavaScript beginner, integrating new code sni ...

What benefits can be gained from utilizing the beforeEach function within Jest testing?

I am currently immersing myself in the world of Jest by following this informative guide. Can you explain the benefits of utilizing the beforeEach function in Jest? I have a particular interest in identifying action dispatches. I believe that two segments ...

Creating a stylish button using a combination of CSS and Javascript classes within a webpage layout

Is it feasible to include a button in the layout that has HTML, CSS styles, and JavaScript functionality? For instance: This button is designed with both CSS styling and JavaScript classes. How can one incorporate CSS and JavaScript along with HTML conte ...

Direct a flow to an unknown destination

What I am trying to achieve is writing a stream of data to nowhere without interrupting it. The following code snippet writes the data to a file, which maintains the connection while the stream is active. request .get(href) .on('response', func ...

403 Malicious Path Middleware Error in Express.js

Encountering an error when sending a post request to my server, but only on the production server - whereas the staging server is functioning properly. Both servers are hosted on AWS Ubuntu instances. Investigating the stack trace, it appears that the err ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Creating a comprehensive Product List using ASP.net C#

Can anyone help me with displaying a product list in ASP.net C#? I am working on an e-commerce website for my thesis and I need to show it in a grid format similar to this example: sample product list. I would like to have a limit of 10 products per page. ...

Encountering the "Cannot set headers after they are sent to the client" error within an Express.js application

In my recent project, I created a middleware to authenticate users and verify if they are verified or not. Initially, when I access protected routes for the first time, everything works fine and I receive success messages along with verification of the JWT ...

Navigating the nuances of working with nullable and non-nullable types using generics

Developing a specialized LookupConverter : JsonConverter class was essential for efficient JSON serialization and deserialization of ILookup objects. Given the complexities arising from dealing with generics and the lack of a public concrete Lookup class, ...

Is it possible for two distinct devices to generate the same HWID using Pushwoosh Cordova API?

Our app relies on HWIDs generated by Pushwoosh to distinguish between devices. After reviewing traffic logs, I noticed a peculiar pattern of what appears to be the same device sending HTTP requests from various ISPs within short time intervals. It seems t ...

Error message: "Unable to locate jQuery file within the node.js + Express application running on Heroku platform."

My current setup involves a node.js application with Express and express-handlebars deployed on Heroku. However, whenever I run the app, the console displays a 404 error for the jquery file, leading to subsequent failures for dependent libraries like Boots ...

A step-by-step guide to thoroughly examining the form status in a React application, allowing for the activation of a previously disabled submit button

When I have an onChange event in React, the state is populated correctly. I disable the form button when a field is empty on submit, but I also want users to be able to go back and fill out those fields. The key issue is that if both fields have data, I wa ...

Angular makes it easy to perform HTTP requests using the `http

Greetings! Here is the JSON data for "names" : [ { "file": "file1.zip", "date": "12-03-2016", }, { "file": "file2.zip", "date": "24-06-2016", }, { "file": "file3.zip", "date": "02-12-2016 ...

Extract the source URLs of all images from a website by utilizing Selenium WebDriver

My wordpress site is filled with thousands of image files, but most of them are unnecessary duplicates that are taking up valuable disk space. I am looking for a solution to identify which images are actually being referenced in the HTML code so that I can ...

Using embedded js files in jQuery's .load() function does not function properly

In the index.html file, I have the code snippet below: <div id="page-insert"></div> function openPage(pageid) { $('#page-insert').load(pageid); } openPage('testpage.html'); Additionally, there are script files embedde ...

Tips for retrieving data using ajax with servlets:

I am trying to send some data on the page to a servlet So I have created the following jQuery code to achieve this I am using all the data to construct a JSON string and send it directly to the servlet However, I am unsure how to retrieve the entire dat ...