Dominik Willaford
Dominik Willaford

Reputation: 313

Controller is returning null after using ajax Post

I have created an ajax Post that targets the action method in my controller called edit, but the problem I am facing is that none of the values are being set to anything but null.

What should be happening is that on '.save-user' button click it should then grab the values using the IDs and store them to local variables which will be used in the JSON.stringify method.

I am new to ajax and jquery so any help or guidance would be greatly appreciated.

My submit button:

@using(Html.BeginForm("Edit", "LansingMileage", FormMethod.Post))
                {
                    <button class="save-user edit-mode" type="submit"name="Save">Save</button>
                }

My JQuery/Ajax:

 $('.save-user').on('.click', function saveClick() {


                var expense = $("#expense").val();
                var travel = $("#travel").val();
                var trip = $("#trip").val();
                var newRecords = jQuery.makeArray(expense, travel,trip);

                var dataToPost = JSON.stringify({ methodParam: newRecords });

                $.ajax({
                    type: "POST",
                    url: "/LansingMileage/Edit",
                    contentType: "application/json; charset=utf-8",
                    datatype: 'JSON',
                    data: dataToPost,
                    traditional: true
                });

Controller:

public ActionResult Edit([Bind(Include = "ExpMonthYr,TripType,TravelDate")]List<LansingMileage> methodParam)
        {


            if (ModelState.IsValid)
            {
                    try
                    {
                        db.Entry(methodParam).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {

                    }
                return RedirectToAction("Index");
            }

            return View(methodParam);
        }

Upvotes: 1

Views: 86

Answers (1)

cvb
cvb

Reputation: 793

EDIT: First your need to fix how your newRecords variable is constructed. I think the issue lies with your usage of jquery.makeArray. Try creating an object, in Javascript, whose keys match the properties of your C# object. Give it the appropriate values then push that object to an array.

This should fix your issue because right now your controller is expecting a list (in javascript terms an array).

What your passing to the stringify method is an object which has a key whose value is the array whereas you should just be stringifying or sending the array to match your controller parameter.

Upvotes: 1

Related Questions