javascript - 如何将包含 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 对象内部列表的问题。
我究竟做错了什么?
解决方案
items
在您的 json 对象中是一个列表。因此,您需要将Items
c# 模型中的类型更改为列表。
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; }
}
}
推荐阅读
- c# - 当我从我的 API 使用 Post 插入数据库时出现异常
- python - 使用 Anaconda 将 Django 应用程序部署到 Heroku 时出现“没有这样的选项:--allow-all-external”
- python - 重塑 NumPy 数组:IndexError:元组索引超出范围
- python - 更改字符串中某些字符大小写的函数
- rust - rust中Option的实际用途是什么?
- go - 无法在全新的 Go 项目中加载包
- pandas - 通过定时数据和交叉验证避免数据泄漏
- firebase - Firebase Cloud Functions - 使用 firebase 功能测试功能时出现身份验证错误:shell
- javascript - 以父组件内的对象形式从所有子组件获取合并数据:React JS
- python - 如何将具有多个页面和内部链接的网站抓取到熊猫数据框中?