【问题标题】:JSON Array not Binding to MVC ModelJSON 数组未绑定到 MVC 模型
【发布时间】:2016-03-19 05:25:24
【问题描述】:

我通过 AJAX 调用将 json 数据列表传递给控制器​​。 字符串数组“LandPhone、Mobile 和 Email”在控制器中变为空。实际上有一些价值。

主模型

public class CustomerModel
{
    public string ReferenceId { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string TINNo { get; set; }
    public string CurrencyId { get; set; }
    public List<CustomerAddressModel> Address { get; set; }

}

子模型

public class CustomerAddressModel
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string AddressLine3 { get; set; }
    public int ZipCode { get; set; }
    public string District { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string[] LandPhone { get; set; }
    public string[] Mobile { get; set; }
    public string[] Email { get; set; }

}

AJAX 调用

function get() {
$.ajax({
    type: 'POST',
    url: '/temp/Customer',
    data: { "ReferenceId": "", "FirstName": "", "MiddleName": "", "LastName": "", "TINNo": "", "CurrencyId": 0,
            "Address": [{
                "AddressLine1": "", "AddressLine2": "", "AddressLine3": "", "ZipCode": 0, "District": "", "State": "", "Country": "",
                "LandPhone": ["123"],
                "Mobile": ["1234567890", "9876543210"],
                "Email": ["a@b.com", "b@c.com"]
            }]
     },
    dataType: "json",
    //contentType: "application/json;charset=utf-8",
    async: false,
    success: function (data) {
        alert(data);
    }
});

在控制器方法中数据变成这样

【问题讨论】:

    标签: jquery arrays json ajax asp.net-mvc


    【解决方案1】:

    您需要包含contentType: "application/json;charset=utf-8", 选项并将数据字符串化

    $.ajax({
        type: 'POST',
        url: '@Url.Action("Customer", "temp")', // don't hard code
        contentType: "application/json;charset=utf-8"
        data: JSON.stringify({ "ReferenceId": ..... "Address": [{ "AddressLine1": "" ... }]}),
        ....
    

    【讨论】:

    • 就我而言,我还必须将[FromBody] 添加到控制器方法中。我正在使用 ASP.NET Core 2.0。
    猜你喜欢
    • 2021-07-21
    • 1970-01-01
    • 2014-05-31
    • 2015-03-20
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多