简体   繁体   English

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

[英]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. 发送复杂对象时, List<Order> null在我的控制器操作方法中返回null Can someone help to identify the issue? 有人可以帮助确定问题吗? Do we need to pass array of objects with indexes? 我们需要传递带索引的对象数组吗?

JavaScript 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 MVC

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

C# 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. Orders目前没有访问修饰符,因此它是私有的。

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. 除此之外,一切看起来都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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