0

On MVC side I have a class like this:

public class ComplexOne
{
   public DateTime Date {get;set;}
   public int Value {get;set;}
}

And in controller action

public virtual JsonResult TakeData(int id, ComplexOne[] data)  

From JS I'm sending object like this:

{
id = 10,
data = [
        {Date:"2017-12-27", Value:10},
        {Date:"2017-12-27", Value:20},
        {Date:"2017-12-27", Value:30}
    ]
}

MVC understands all except Date, which deserializes as default value ({01.01.0001 0:00:00}). I've tried different date formats - yyyy-MM-dd, dd-MM-yyyy, MM/dd/yyyy and even ISO one, but got no luck.

How to do this in correct way without passing date as string and manual parsing in MVC?

8
  • Because in your class you have DateTime object but you are passing date as string to deserialize. Commented Dec 27, 2018 at 10:22
  • There's no problem in other cases; even more in ISO format the full date and time are passed. Commented Dec 27, 2018 at 10:25
  • I think it expects date with time in the string. or try creating DateTime Object like {Date: new DateTime(2015,06,27), Value: 10} Commented Dec 27, 2018 at 10:33
  • @TrolltheLegacy Is that class shown exactly as how you have in your code? The shown class is private and has private fields. I am uncertain that what is shown binds to anything. Provide a minimal reproducible example that represents the actual problem. Commented Dec 27, 2018 at 10:37
  • @varatharajan Then browser sends ugliest datetime string I've seen and again with no luck. Commented Dec 27, 2018 at 10:42

1 Answer 1

0

You are passing Date as string in the JSON object but your Date in ComplexOne model class is DateTime.

So you can use DTO to receive the JSON object in the controller action and then convert the DTO to actual model as follows:

public class ComplexOneDto
{
   public string Date {get;set;}
   public int Value {get;set;}
}

The controller action:

public virtual JsonResult TakeData(int id, ComplexOneDto[] data)
{
    // here convert the ComplexOneDto[] to ComplexOne[] as follows

    List<ComplexOne> complexOnes = new List<ComplexOne>();
    foreach (ComplexOneDto complexOneDto in data)
    {
       DateTime convertedDateTime = DateTime.ParseExact(complexOneDto.Date, "yyyy-MM-dd", CultureInfo.InvariantCulture);

       complexOnes .Add(new ComplexOne() { Date = convertedDateTime, Value = complexOneDto.Value });
    }

    return Json(true);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.