1

I need to save data to a database from my MVC ASP.net project without refreshing the view page. To do this I plan to create a string and send it to the controller to then send to the database. I have already made a function to create the string...

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);

    }

And an example of the string looks like this

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

How can I 1.) Send this string to the controller and 2.) Use the controller to send this to my database?

All data points correspond to table RecordEntry in my database and have the same name as given.

EDIT: This is my function in view now. When ran it does not get down to the alert(chain). Do you know why? The other alert that is commented out does hit.

EDIT: I realized that you did not have the ajax within the function and I did there. Should it be in the function so it is called on a submit button press?

    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 my submit (next) button

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

And the function that is called that calls multiple other functions.

    function NextButtonClick() {

        HideSelectionsBeforeNextSelection();
        ShowDropDownsAgain();
        //removefromList();
        ResetValues();
        IncreaseRecordIdByOne();
        CreateChain();
    }
6
  • you can just post the form using JS "ajax" call... no need to build a string. Your controller will bind the form data to a model/class in the controller. (I return JSON to tell the JS what to load into the DOM on completion of database update... in my case it's a razor page minus layout stuff) Commented Aug 2, 2021 at 19:01
  • Interesting. I am very new to this and didn't realize that could be done. Do you have an example ajax function you could share? Commented Aug 2, 2021 at 19:03
  • you have some issues on the fundamentals of net, controllers and json, i suggest you to go and read the basics of how a controller works, since you can send a Json object with the same schema on your controller and it will be auto casted on the server, then you can send the object via fetch, jquery or a httprequest via javascript Commented Aug 2, 2021 at 19:04
  • I have a decent grasp of how net, controllers, and json work. I realize I could've made my string formatted better to be handled as a json. I also realize I can send a json to the controller. I just didn't know how to handle it inside of the controller really. Is there an easy action that processes a json into the database? Commented Aug 2, 2021 at 19:09
  • you can serialize for standard form data: jQuery Example: formresult = $('#' + formID).serialize() +'&otherparam=' + otherparam; $.post(destURL, formresult, function (data) { .... })... if you are uploading a file just use formdata: var formData = new FormData(thisForm); and jQuery.ajax( type: 'POST', url: destURL, data: formData, ... }, error: function (jqXHR, textStatus, error) { .... } }); Commented Aug 2, 2021 at 21:39

1 Answer 1

1

Try this

javasript

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

you have to create 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");
}

}
Sign up to request clarification or add additional context in comments.

4 Comments

@Three33Steele you shoud add another } - return { ....... "WorkOrderNumber": WorkOrderNumber }; } or if you want to use only one function check my updated answer
So do I need to call that ajax function on a submit button press?
pls show your submit buttorn press. You can separate this into 2 functions or use as one. It is up to you
@Three33Steele You have got the answer for the first question. As I told you before- one question, one answer. If you have a problem to save data to db it will have to post another question and the answer should be very very big.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.