首页 > 解决方案 > 如何将包含 js 对象的列表转发到 asp.net core mvc?

问题描述

我生成了js对象,如下所示:

cartStorage = {
     name: 'testcustomer',
     email: 'test@gmail.com',
     items: [
             {
               licenseName: 'Private',
               licensePrice: 2
             },
             {
               licenseName: 'Public',
               licensePrice: 4
             }
            ],
     totalPrice: 6
}

然后我使用 ajax 将此对象传递给 mvc 控制器

$.ajax({
        url: '/TestPayment/ChargeTest',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(cartStorage),
        success: function(response){
            if (response != null) {  
                alert(response);  
            } else {  
                alert("Something went wrong");  
            }  
        }    
    });

这是与此方法关联的视图模型

namespace Web.ViewModels.Payment
{
    public class Items
    {
        public string licenseName { get; set; }
        public int licensePrice { get; set; }
    }

    public class PayerInfo
    {
        public int totalPrice { get; set; }
        public string name { get; set; }
        public string email { get; set; }
        public Items Items { get; set; }
    } 
}

这是处理ajax请求的mvc控制器方法

   [HttpPost]
        public ContentResult ChargeTest([FromBody] PayerInfo model)
        {
            String FullName = model.name;
        }

但是当服务器执行控制器方法时,模型结果为空。

但是,如果我在视图模型中注释掉 Items 类和 PayerInfo 类中的实例创建,则模型被成功转发并存储了所有数据,我只是遇到了 js 对象内部列表的问题。

我究竟做错了什么?

标签: javascriptc#asp.net-mvc

解决方案


items在您的 json 对象中是一个列表。因此,您需要将Itemsc# 模型中的类型更改为列表。

namespace Web.ViewModels.Payment
{
    public class Items
    {
        public string licenseName { get; set; }
        public int licensePrice { get; set; }
    }

    public class PayerInfo
    {
        public int totalPrice { get; set; }
        public string name { get; set; }
        public string email { get; set; }
        public List<Items> Items { get; set; }
    } 
}

推荐阅读