没有正确设置数组的MVC JSON对象

MVC JSON object with array not set properly

本文关键字:MVC JSON 对象 数组 设置      更新时间:2023-09-26

我正在制作一个工具,在这个工具中可以获得一个引语抛出javascript,然后发送自己的引语。报价单制作正常,但发送邮件时,报价单数据损坏。
Quotation对象中除Options数组外的数据正常。当发送3个数组项目时,Options数组保存3个项目,除了它们的名称为空且价格为0

报价发送给ASP。. NET MVC 3使用jQuery.post .

c#中的引号对象如下:
public class Quotation
{
    public string Email { get; set; }
    public string Product { get; set; }
    public int Amount { get; set; }
    public decimal BasePrice { get; set; }
    public decimal SendPrice { get; set; }
    public Option[] Options { get; set; }
    public decimal Discount { get; set; }
    public decimal SubTotal { get; set; }
    public decimal TotalPrice { get; set; }
}
public class Option
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

动作方法如下:

[HttpPost]
public JsonResult Offerte(Models.Quotation quotation)
{
    //
}

jQuery看起来像:

$.post(baseUrl + "/api/Offerte/", jsonContent, function (data) {
    alert(data.Message);
});

jsonContent对象看起来像:

{
    "Options":[
        {
            "Name":"Extra pagina's (16)",
            "Price":40
        },
        {
            "Name":"Papier Keuze",
            "Price":30
        },
        {
            "Name":"Omslag",
            "Price":29.950000000000003
        }
    ],
    "Amount":"5",
    "BasePrice":99.96000000000001,
    "SubTotal":199.91000000000003,
    "SendPrice":0,
    "Discount":19.991,
    "TotalPrice":179.91900000000004,
    "Email":"someone@example.com"
} 

有人知道为什么数组没有正确设置吗?


编辑
如果我将这个调试代码添加到控制器中:

using (var writer = System.IO.File.CreateText(Server.MapPath("~/App_Data/debug.txt")))
{
    writer.AutoFlush = true;
    foreach (var key in Request.Form.AllKeys)
    {
        writer.WriteLine(key + ": " + Request.Form[key]);
    }
}

Options[0][Name]: Extra pagina's (52)
选择[0][价格]:156
选项[1][Name]: Papier Keuze
选择[1][价格]:68.4
选择[2][名字]:Omslag
选择[2][价格]:41.94
数量:6
BasePrice: 149.91899999999998
小计:416.25899999999996
SendPrice: 0
折扣:45.78848999999999
TotalPrice: 370.47051
电子邮件:someone@example.com

这意味着数据确实到达了控制器,但Options仍然没有被正确设置。我不想要一个简单的修复,我自己解析之后,我想知道正确的方式来处理它,所以MVC会照顾它

如果你想要发送JSON数据到ASP. js . js. NET MVC控制器动作,并且你希望当前模型绑定工作(例如在你的模型上绑定集合),你需要指定contentType为"aplication/json"

因为$.post你不能指定内容类型你需要使用$.ajax你还需要JSON.stringify你的数据:

$.ajax({
    url: baseUrl + "/api/Offerte/",
    type: 'POST',
    data: JSON.stringify(jsonContent),
    contentType: "application/json",
    success: function (data) {
        alert(data.Message);
    }
});