我试图将JSON数据从AngularJs $http发布到ASP.NET MVC控制器。这是json数据示例:

     var postdata = {
        Email: "[email protected]",
        selectedanswer: {0: 3, 1: 2, 2: 0, 3: 3, 4: 1}
    };


AngularJs代码:

    $http({
        url: "/page/PostFileWithData",
        headers: {
           'Content-Type': 'application/json; charset=utf-8'
        },
        method: "POST",
        dataType: "json",
        traditional: true,
        data: JSON.stringify(postdata)
    }).success(function (data) {
        console.log(data);
    }).error(function (data) {
        console.log('fail');
    });


控制器:

    public JsonResult PostFileWithData(UserModel userdata)
    {
        UserModel udata = new UserModel {
            Email = userdata.Email
            selectedanswer = userdata.selectedanswer
        };

        return Json(udata, JsonRequestBehavior.AllowGet);
    }


我的模特:

    public class UserModel {
        public string Email { get; set; }
        public string selectedanswer { get; set; }
    }


现在的问题是我在console.log中获得了email字段正常,但是selectedanswernull

像这样

    { Email: "[email protected]", selectedanswer: null }

最佳答案

由于您要从Ajax传递键值对象,因此将模型更改为

public class UserModel
{
    public string Email { get; set; }
    public Dictionary<int,int> selectedanswer { get; set; }
}


或者,以如下形式发送selectedanswer字符串:

var postdata = {
    Email: "[email protected]",
    selectedanswer: "{0: 3, 1: 2, 2: 0, 3: 3, 4: 1}"
};


希望这可以帮助。

09-18 17:10