0

After saving DateTime in controller, I pass it back to the View but when it's displayed in view the value became /Date(1545062400000)/.

I already checked in the controller while in process if the data was changed but it did not since I'm just passing the viewmodel in the view.

[HttpPost]
    public ActionResult UpdateHeader(RecordViewModel recordViewModel)
    {
        var ResultMessage = "";
        if (ModelState.IsValid)
        {
            Record record = (from c in context.Records
                                           where c.RecordId == recordViewModel.RecordId
                                           select c).FirstOrDefault();
            if (record == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            record.Description = recordViewModel.Description;
            record.Date = recordViewModel.Date;
            record.Remarks = recordViewModel.Remarks;
            try
            {
                context.SaveChanges();
                ResultMessage = "Record successfully updated.";
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ErrorHelper.GetInnerException(ex));
                ResultMessage = "Error: " + ErrorHelper.GetInnerException(ex);
            }
        }
        var result = new { Model = recordViewModel, ResultMessage = ResultMessage };
        return Json(result, JsonRequestBehavior.AllowGet);
    }

Angular

self.submitEdit = function () {
        var updateRecordHeader = RecordServices.updateRecordHeader(self.header)
        .then(function successCallback(response) {
            self.header = response.data.Model;
            self.header.ResultMessage = response.data.ResultMessage;
        }, function errorCallback(response) { toastr.error(response.statusText); });
    }
Len
  • 534
  • 1
  • 15
  • 31
  • Which property contains `DateTime` type? What you see is tick value of the actual `DateTime` struct, it's serialized in number of milliseconds since epoch (1970/01/01). You can create a function to return it as proper JS `Date` object. – Tetsuya Yamamoto Dec 13 '18 at 06:14
  • @TetsuyaYamamoto record.Date – Len Dec 13 '18 at 06:20

1 Answers1

1

The /Date(1545062400000)/ is known as date ticks using UNIX timestamp format since RFC7519 "epoch" (January 01, 1970), which cannot be directly consumed as JS Date object without converting it first. The reason behind usage of the ticks is JSON format doesn't have specific representation for DateTime struct when serialized to plain strings (see this reference).

You can create a custom function to convert ticks into JS Date object:

function toJSDate(value) {
   var regex = /Date\(([^)]+)\)/;
   var results = regex.exec(value);
   var date = new Date(parseFloat(results[1])); // or parseInt
   return date;
}

Or even simpler without regex by picking numeric values directly like this:

function toJSDate(value) {
   var date = new Date(parseFloat(value.substring(6))); // or parseInt
   return date;
}

Then use that function for ticks-to-date conversion:

// example
var header = response.data.Model;
var dateObject = toJSDate(header.Date);

// assign date object afterwards

Note that you may need to create another object structure which resembles response.data.Model but using server-side Date property with JS date object.

As an alternative you may create a getter-only string property which uses ToString() to convert DateTime value into desired string representation, then use it inside JS.

Side note:

Avoid using viewmodel property name which exactly matches built-in JS function names & objects (i.e. Date) for clarity.

Related issues:

How do I format a Microsoft JSON date?

Converting .NET DateTime to JSON

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61