Note that there are some explanatory texts on larger screens.

plurals
  1. PODe-serializing object in MVC4 action results in null values
    text
    copied!<p>I am using jQuery 1.9.1 and MVC 4.</p> <p>I have the following javascript:</p> <pre><code>$.ajax({ url: '/Home/doSomething', type: 'POST', data: JSON.stringify({ devices: [{ Id: 123, Name: "something", MapName: "map" },{ Id: 321, Name: "a name", MapName: "another map" }] }), dataType: 'json', contentType: 'application/json' } </code></pre> <p>And the following c# in my HomeController:</p> <pre><code>[HttpPost] public string doSomething( Device[ ] devices ) { //stuff consuming that array } </code></pre> <p>The Device class is defined like this:</p> <pre><code>[Serializable] public class Device { public long Id; public string Name; public string MapName; } </code></pre> <p>According to the debugger, the devices array is a 2-element array with all properties of each Device element being null.</p> <p>According to chrome, the post data looks like this:</p> <pre><code>{ "devices": [ { "Id": 123, "Name": "something", "MapName": "map" }, { "Id": 321, "Name": "a name", "MapName": "another map" } ] } </code></pre> <p>What is wrong here that is making MVC swear up and down that those objects are null, yet still giving me an appropriate-length array of them?</p> <p>I have tried posting the array directly, without calling JSON.stringify on it. I have tried posting the array inside an object as a property called "devices", again without strigifying it. I have tried posting the array inside an object as a property called "devices", while only stringifying the array itself.</p> <p>All of these result in bad behavior of one form or another. Either chrome does not post the appropriate data in the first place, or MVC does not de-serialize it.</p> <p>I have scoured the web and can't seem to find any examples of why this should be broken.</p> <p><strong>Edit 2013-02-21 13:12 UTC-5:</strong></p> <p>I have also tried this without using JSON and just letting jQuery post it as form data. Here is the code for that:</p> <pre><code>var postData = { devices: [{ Id: 123, Name: "something", MapName: "map" }, { Id: 321, Name: "a name", MapName: "another map" }] }; $.ajax({ url: '/Home/doSomething', type: 'POST', data: postData }); </code></pre> <p>And the C# is still the same as above.</p> <p>The behavior is still the same as when it was JSON, though. MVC sees an array of 2 elements, but all values of the objects in that array are default (0 for the integer and null for the strings).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload