简体   繁体   中英

Unable to send JSON data to MVC controller

I have a JavaScript function that looks as follows:

function exportToExcel() {
    $.ajax({
        url: "/eBird/ExportToExcel",
        data: jsonSightingData,
        type: 'POST',
        contentType: 'application/json'
    });
} 

My MVC controller looks like this:

    public ActionResult ExportToExcel(List<Entities.MyClass> data)
{
    try
    {
        ...
    }
    catch (System.Exception exception)
    {
       ...
    }

MyClass defintion is:

   public class MyClass
    {
        public string comName { get; set; }
        public int howMany { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
        public string locID { get; set; }
        public string locName { get; set; }
        public bool locationPrivate { get; set; }
        public string obsDt { get; set; }
        public bool obsReviewed { get; set; }
        public bool obsValid { get; set; }
        public string sciName { get; set; }
    }

The class matches the JSON data coming in exactly. The problem is that when my controller method is called, 'data' is always NULL. My understanding was that the MVC model binder would automatically bind the JSON data to my MyClass list. But it doesn't appear to be working.

Sample JSON is as follows:

[{"comName":"Great Black-backed Gull","lat":42.4613266,"lng":-76.5059255,"locID":"L99381","locName":"Stewart Park","locationPrivate":false,"obsDt":"2014-09-19 12:40","obsReviewed":false,"obsValid":true,"sciName":"Larus marinus"}]

Use a General Object (Like JContainer) to "capture" the incoming data. or even Object if you are not sure what you get. Then see what you have inside. I use an external deserializer to convert json back to class. (using .ToString() to make it readable to the serializer)

(try Json.Net)

Also - make sure that the JSON is not converted into Unicode. I've had an issue with that as well.

another remark - I think content type should be application/json. Read this: SO about json content type

Run Fiddler and capture Json sent to controller. The controller expects a List but looks like you are sending single object. Stuff coming in as null happens to many of us. I'll try and run what you have. Can you also mess with controller and give it just MyClass coming in?

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