简体   繁体   中英

Json Received data = null

Hi I have json request like here:

$.ajax({
        url: "/DeviceUsage/FreeDevice",
        type: "POST",
        data: JSON.stringify({ data: Ids }),
        error: function (data) {
            alert("error " + data);
        },
        success: function (data) {
            if (data === "") {
                alert("succes")
            }
            else {
                alert(data);
            }
        }
    });

where Ids = var Ids = new Array(); ( full of ints)

My Json looks like this:

{"data":[38,40,41]} 

method where I'm receiving Json:

[HttpPost]
public JsonResult FreeDevice(FreeDeviceModel m)
{
    return Json("");
}

and my ViewModel:

public class FreeDeviceModel
{
    public List<int> data { get; set; }
}

I cross checked everything with Json validator, Json2C#

and eveything looks correct so why nothing is reveived by the FreeDevice method?

For clarification I have problem with this : 数据应为3个元素的列表,但为Null

Data shoudl be List of 3 elements but is Null

Check Below Code it should work

Json Call

var FreeDeviceModel = {};
FreeDeviceModel.data = new Array();
FreeDeviceModel.data[0] = 39;
FreeDeviceModel.data[1] = 40;
FreeDeviceModel.data[2] = 41;
var object = JSON.stringify({ FreeDeviceModel: FreeDeviceModel });
$.ajax({
    type: "POST",
    url: "/Home/FreeDevice",
    contentType: 'application/json; charset=utf-8',
    data: object,
    dataType: 'json',
    cache: false,
     error: function (data) {
        alert("error " + data);
    },
    success: function (data) {
        if (data === "") {
            alert("succes")
        }
        else {
            alert(data);
        }
    }
});

Controller Call

  [HttpPost]
    public JsonResult FreeDevice(FreeDeviceModel FreeDeviceModel)
    {
        return Json("");
    }

Did you try setting the dataType to JSON

dataType: 'json',
data: {"data":[38,40,41]} 

Hope it helped...

Ok. Adding this line:

contentType: "application/json; charset=utf-8",

fixed everything!

You should try something like this:

public JsonResult FreeDevice(string details)
{
FreeDeviceModel tempRecord = JsonConvert.DeserializeObject<List<FreeDeviceModel>>(details);
}

你试一试:

data: JSON.stringify(Ids), 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM