通过AJAX POST将JSON传递给具有多个模型和/或参数的Controller

时间:2015-07-01 01:04:01

标签: javascript jquery ajax json asp.net-mvc-4

我写了这个控制器:

[HttpPost]
    public JsonResult CheckOut(List<POS_model> pos, double totalPayment)
    {
        try
        {
            var json = JsonConvert.SerializeObject(pos);
            DataTable posTable = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
            posTable.Columns["discount_percent"].ColumnName = @"Discount %";

            POS m_pos = new POS();
            m_pos.Data = posTable;
            m_pos.totalPayment = totalPayment;
            m_pos.CheckOut();

            return Json(new
            {
                Status = "Success"
            });
        }
        catch
        {
            return Json(new
            {
                Status = "Fail"
            });
        }
    }

我尝试编写这个AJAX脚本来调用并将参数提交给Controller :(但它没有用)

var totalPay = 1000;
var GatherPosItems = $('#tblPOS').tableToJSON();

$.ajax({
        type: 'POST',
        data: JSON.stringify(GatherPosItems)+"&totalPayment="+totalPay,
        url: '@Url.Action("CheckOut", "POS")',
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert('Success');
        },
        error: function (req, status, errorObj) {
            alert(errorObj.toString());
        }
        });

GatherPosItems是一个带有多个&#34;行&#34;的JSON。或对象,所以它是一个数组。

我添加了参数totalPayment

如何将GatherPosItemstotalPayment传递给控制器​​?

我的模特:

public class POS_model
{
        public string Qty { get; set; }
        public string description { get; set; }
        public string price { get; set; }
        public string discount_percent { get; set; }
        public string Discount_amount { get; set; }
        public string Discounted_price { get; set; }
        public string Line_total { get; set; }
        public string is_vat { get; set; }
        public string track_type { get; set; }
        public string item_line_id { get; set; }
        public string id { get; set; }
        public string sale_code { get; set; }
        public string reference { get; set; }
        public string unit_of_measure { get; set; }
        public string location { get; set; }
        public string item_code { get; set; }
}

我的GatherPosItems结果: enter image description here

1 个答案:

答案 0 :(得分:2)

将非JSON字符串(&totalPayment="+totalPay)连接到从JSON.stringify函数返回的JSON,这会破坏发送到服务器的数据格式,并使模型绑定器无法解析它。

以下内容应该有效:

$.ajax({
    type: 'POST',
    data: JSON.stringify({pos: GatherPosItems, totalPayment: totalPay}),
    url: '@Url.Action("CheckOut", "POS")',
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function(data) {
        alert('Success');
    },
    error: function(req, status, errorObj) {
        alert(errorObj.toString());
    }
});