将ajax中的复杂对象发送到MVC

时间:2015-06-13 13:38:16

标签: javascript c# ajax asp.net-mvc

发送复杂对象时,List<Order>的值在我的控制器操作方法中返回null。有人可以帮助确定问题吗?我们需要传递带索引的对象数组吗?

的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; }
}

1 个答案:

答案 0 :(得分:8)

您需要使用 public 属性进行模型绑定。 Orders目前没有访问修饰符,因此它是私有的。

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

除此之外,一切都很好。