1

I have some Json that I'm posting back using ajax; the object is build in JavaScript on the client side and received on the MVC side by a C# object with the same property names. I had a mixture of nullable and non-nullable fields and everything was working fine. While making a modification I changed a non-nullable long property to nullable since it won't be set in all situations.

JavaScript

var dataToSend = {
    TestId1: 1,
    TestId2: 2,
    TestId3: 3,
    Action: 'add'
};

$.ajax({
    url: '/testRequestUrl/SaveTestRequest',
    type: 'POST',
    contentType: "application/json",
    data: JSON.stringify(dataToSend)
}).done(function(returnData) {
    alert(returnData);
});

MVC

public class TestRequest
{
    public int? TestId1 { get; set; }
    public int? TestId2 { get; set; }
    public long? TestId3 { get; set; }
    public PostAction Action { get; set; }
}

[HttpPost]
public ActionResult SaveTestRequest(TestRequest request)
{
    // Do some processing and return the result
    var result = DoSomeProcessing(request);
    return Json(result);
}

Originally TestId3 was not nullable and everything worked; once I changed TestId3 to nullable only that field stopped loading the data from the client. I've checked my JSON and TestId3 is getting its value set on the client side but just not making it to the server side. As you can see I have other nullable fields and they are getting their data set just fine so I'm wondering why only the changed field isn't working.

Thanks in advance for any help.

Beehive Inc
  • 315
  • 1
  • 3
  • 16
  • possible duplicate of [MVC 3 doesn't bind nullable long](http://stackoverflow.com/questions/6061291/mvc-3-doesnt-bind-nullable-long) – Faust Feb 25 '14 at 20:13
  • Thanks your post was the fix; I figured it was a nullable issue not specifically a nullable long issue. – Beehive Inc Feb 25 '14 at 20:19
  • @CodeMonkey I am having the same exact issue. How did you resolve this? – EagleFox May 28 '14 at 15:50
  • 1
    For a nullable long the value needs to be enclosed in quotes...this is an issue with Microsofts JSON parser. It handles other nullable types except long. – Beehive Inc May 28 '14 at 15:54
  • Thanks @CodeMonkey You are right. I changed my model on the client side and changed it to string. Now it works. – EagleFox May 28 '14 at 15:58
  • I've read that JSON.Net doesn't have this issue and also works for enumerations but the project I'm working on at work is too big to change so I'm just using this work around. – Beehive Inc May 28 '14 at 16:01

1 Answers1

0

This is fixed by putting the data that will be assigned to a nullable long in quotes in the json being passed to the server side.

Beehive Inc
  • 315
  • 1
  • 3
  • 16