4

I am trying to post array of a simple object to my MVC core controller with the Frombody attribute, but for some reason it coming as null. If I post just a single object it is working fine here is my code:

$(document).ready(function() {
    var tk = new Array();

    $("#calendar").fullCalendar({

        header: {
            left: 'prevYear,prev,next,nextYear',
            center: 'title',
            right: 'month,agendaWeek,agendaDay',
        },

        defaultView: 'month',
        editable: true,
        alldayslot: false,
        selectable: true,
        slotminutes: 15,
        nextDayThreshold: "00:00:00",
        events: "/Home/FullCalendar",
        eventDrop: function(event, delta, revertFunc)
        {
            Update(event);
        },
    });

    function Update(event) {
        var datarow =
            {
                "id": event.id, 
                "start": event.start,
                "end": event.end,
            }
        tk.push(datarow);

        debugger;
        confirm(("Save changes?"))
        console.log(JSON.stringify(datarow));
        $.ajax({
            type: "post",
            dataType: 'json',
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(tk),
            url: '@Url.Action("JSON", "Home")',
            success: function (data) {
                debugger;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                debugger;
            }
        });
    }
});

My Controller class

[HttpPost]
public IActionResult UpdateTask([FromBody] List<Task_fullcal> td)
{
    // Do something
    // td is always null if passed as an array 
    //td working fine if passed as single value
}
4
  • 1
    data: JSON.stringify({ tk: tk }), Commented Oct 15, 2016 at 7:30
  • Thanks Stephen for your reply but it is still not working. I am still getting null reference in the controller and this is what I get in the request body. [{"id":6,"start":"2016-10-03T00:30:00","end":null},{"id":7,"start":"2016-10-04T00:10:00","end":"2016-10-05T01:00:00"}] Commented Oct 15, 2016 at 9:45
  • Does Task_fullcal contain properties int id, DateTime start and DateTime end? (and that was supposed to be { td: tk } (not { tk: tk })) Commented Oct 15, 2016 at 9:48
  • Yes this is the model. public class Task_fullcal { public int id { get; set; } public DateTime start { get; set; } public DateTime end { get; set; } } it seems like Fullcalendar is sending the array as query string . but i don't know how to get the query string into my action method Commented Oct 15, 2016 at 10:32

3 Answers 3

1

I had the same problem and I spent few hours to figure out. I wrote the solution in

Pass array of objects to controller by jQuery AJAX, action data is always null in ASP.NET Core 2.2 MVC - it is working with .NET Framework 4.5

Follow below:


I'm working in .Net Core 3.1 and this works for me:

1. Controller

Try [FromForm] instead [FromBody]

    [HttpPost]
    public ActionResult CreateOrdersPOSTObject([FromForm] List<T_POS_ENT_ORDER_DETIALS_Temp> prm)
    {
        //your logic...
        return Json(new { msg = "Successfully added " });
    }

2. AJAX Call

Neither JSON.stringfy() nor contentType should be used.

            var DATA = [];
            DATA.push({ LocPrice: "12", LocProductID: "1002", discount: "0", posNumber: "1", productName: "soap", productQynt: "1" });
            DATA.push({ LocPrice: "23", LocProductID: "1003", discount: "0", posNumber: "1", productName: "shampoo", productQynt: "1" });
            DATA.push({ LocPrice: "7",LocProductID: "1004" ,discount: "0",posNumber: "2" ,productName: "sponge",productQynt: "2"});

            $.ajax({
                url: '@Url.Content("~/home/CreateOrdersPOSTObject")',
                data: { "prm": DATA },
                type: "POST",
                dataType: "json",
                async: true
            });

Or if you prefer, you can use the shorthand $.post with the same results

            var DATA = [];
            DATA.push({ LocPrice: "12", LocProductID: "1002", discount: "0", posNumber: "1", productName: "soap", productQynt: "1" });
            DATA.push({ LocPrice: "23", LocProductID: "1003", discount: "0", posNumber: "1", productName: "shampoo", productQynt: "1" });
            DATA.push({ LocPrice: "7",LocProductID: "1004" ,discount: "0",posNumber: "2" ,productName: "sponge",productQynt: "2"});

            $.post(
                '@Url.Content("~/home/CreateOrdersPOSTObject")',
                { "prm": DATA },
                function () {
                  alert( "success" );
                })
              .fail(function() {
                alert( "error" );
              });
Sign up to request clarification or add additional context in comments.

1 Comment

+1000 for the hint of not using contentType. Thanks!
0

remove FromBody in your action, for complex types the Request will contain complex types in Request body. try use PostMan and try different options.

1 pass object in URL , use [FromUri]

2 pass object in body ,remove FromBody

3 pass simple values like string ,use [FromUri] if you want to access from URL

4 pass simple values like string in Request body ,use [FromBody]

Comments

0

In my case, I converted it to a JSON string in the view:

var seatsJson = JSON.stringify(seats);

Then, in the action, I used Newtonsoft to cast it to an array of objects:

var seats = JsonConvert.DeserializeObject<SeatsModel[]>(seatsjson);

Comments

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.