0

I am trying to submit a form with JQuery to C#, using a Value Tuple as one of the properties of the target object. However, it doesn't seem to work; which I am guessing has something to do with how Value Tuples are constructed, as you also get errors when passing in values in the same manner Obj.Prop=x&etc.. to objects without a default constructor.

Below is what I am doing. I am wondering if there is a way to do it in a similar manner. I know I could create an object matching the Tuple in it's place or break the properties up and manually alter the serialization string; but I was hoping to avoid those if possible.

$.ajax({
    url: '.../MyMethod',
    data: $('#MyForm').serialize(),
    succss: function (result) {
        blah();
    },
    error: function (e) {
        blah();
    }
});

The form serialization creates:

Id=4&Time.Hour=16&Time.Minute=30

MyMethod has a parameter of SubmissionObject submission which looks like:

public class SubmissionObject 
{
    public long Id { get; set; }
    public (short Hour, short Minute) Time { get; set; }
}

However, the object will populate as

    Id: 4
    Time: (0, 0)

instead of

    Id: 4
    Time: (16, 30)
v07
  • 11
  • 3
  • Tuples are immutable. Default json deserialization works by initializing empty instances and then setting members, which you can't if the instance is immutable. Why not create a class instead of a tuple? – Chronicle Mar 05 '20 at 03:16
  • @Chronicle in the actual code I have quite a few repeats of the Time objects, which are each named differently within the Html. I was hoping to avoid renaming them to match a single object, as the state they are in for the Submission is a one off and the only time that object would be used. It's my backup plan if there is no way to salvage this though – v07 Mar 05 '20 at 03:21
  • In that case you can write your own json deserialization in a `JsonConverter`. [The answer here](https://stackoverflow.com/questions/40439290/custom-deserialization-using-json-net) has an example: it's not exactly like what you are doing but it's got the methods you need. Create a custom class and deserialize differently named values dynamically to the same property – Chronicle Mar 05 '20 at 03:27

0 Answers0