从ajax中诊断mvc中的JS模型绑定器问题

时间:2016-03-11 12:16:06

标签: c# jquery ajax asp.net-mvc

我无法弄清楚为什么我的行动参数会通过null传递。我也不确定如何诊断问题。我可以看到与数据一起发送的http请求数据,并逐步通过调试器将对象显示为null,不知道如何查看两者之间的步骤。

模型

    public class ComplexObj
    {
        public int Id { get; set; }
        public int Test1 { get; set; }
        public decimal Test2 { get; set; }
    }

    public class BiggerObj
    {
        public BiggerObj()
        {
            ComplexObj = new List<ComplexObj>();
        }

        public long OtherId { get; set; }
        public string Name { get; set; }
        public ICollection<ComplexObj> ComplexObjs { get; set; }
    }

动作

    [HttpPost]
    public void TestAction(BiggerObj[] biggerObjs)
    {
        ...// biggerObjs is null :(
    }

查看

    function ajaxCall() {
        var data = [];

                var bigObj = new Object();
                bigObj.OtherId = 123;
                bigObj.Name = "TestName";
                bigObj.ComplexObj = [];

                var complexObj = new Object();
                complexObj.Id = 789;
                complexObj.Test1 = 123;
                complexObj.Test2 = 456;

                bigObj.ComplexObj.push(complexObj);

                data.push(bigObj);
            }
        }

        $.ajax({
            url: SITEROOT + "myController/TestAction",
            cache: false,
            type: 'POST',
            data: data,
            complete: function() {
                alert('done');
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

解决

您必须使用:

  • JSON.stringify并将contentType声明为"application/json; charset=utf-8"

  • 使用parseFloat() function解析十进制值,默认情况下,十进制被视为int。

将您的操作更改为:

[HttpPost]
        public ActionResult TestAction(BiggerObj[] biggerObjs)
        {            
            ...// biggerObjs is null :(
        }

将ajaxCall功能更改为:

//ajaxCall 
function ajaxCall() {
        var data = [];

        var bigObj = {
            OtherId : 123,
            Name : "TestName",
            ComplexObjs : new Array()
        };

        var ComplexObjs = {
            Id: 789,
            Test1: 123,
            Test2: parseFloat(456) 
// decimal types are considered an integer, you have to parse
        };

        bigObj.ComplexObjs.push(ComplexObjs);

        data.push(bigObj);


        $.ajax({
            url:"/Test/TestAction",
            cache: false,
            type: 'POST',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            complete: function () {
                alert('done');
            }
        });
    }

我测试过,工作正常。