簡體   English   中英

從Ajax診斷MVC中的JS模型綁定程序問題

[英]Diagnosing JS model binder issue in mvc from ajax

我不知道為什么我的動作參數會通過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');
            }
        });
    }

解決了

您必須使用:

  • 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');
            }
        });
    }

我測試了,工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM