简体   繁体   中英

Sending complex object in ajax to MVC

The value of List<Order> returns as null in my controller action method while sending the complex object. Can someone help to identify the issue? Do we need to pass array of objects with indexes?

JavaScript

function OnCustomerClick() {
    //var orders = [];
    //orders.push({ 'OrderId': '1', 'OrderBy': 'Saroj' });

    var complexObject = {
        FirstName: 'Saroj',
        LastName: 'K',
        //Orders : orders
        Orders: [{ OrderId: 1, OrderBy: 'Saroj' }, { OrderId: 2, OrderBy: 'Kumar' }]
    };

    var obj = { customer: complexObject };
    var data2send = JSON.stringify(obj);

    $.ajax({
        type: "POST",
        url: 'Home/TestCustomer1',
        data: data2send,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (arg) { //call successfull
        },
        error: function (xhr) {
            //error occurred
        }
    });
};

MVC

 public ActionResult TestCustomer1(Customer customer)
    {
        return Json(customer);
    }

C#

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    List<order> Orders { get; set; }
}

public class order
{
    public int OrderId { get; set; }
    public string  OrderBy { get; set; }
}

You need to use public properties for model binding. Orders currently has no access modifier, so its private.

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<order> Orders { get; set; } // <----
}

Other than that, everything looks fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM