0

I have a C# model which I return to my view, I then convert this to an array of JSON objects like so:

@{
    string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
var modelData = @Html.Raw(data);

My Model looks like this:

public int Id { get; set; }
public DateTime Date { get; set; }
public decimal Value { get; set; }

When I output the Date it gets output as: Date: /Date(1338279123847)/

Is there anyway I can convert the date to a Javascript date before outputting it on my view, perhaps from within my modelData array? In the form of DD/MM/YYYY

2
  • Is that date copied directly from your code's output? I'm unsure of it's format. I originally though it was a epoch timestamp, but unless the date was originally sometime in May 44,378, I don't think it is. Commented May 29, 2012 at 8:19
  • The Date property in my C# Model is just today's date: DateTime.Now Commented May 29, 2012 at 8:20

1 Answer 1

1

You cannot do that while serializing the model but you could do it afterwards:

<script type="text/javascript">
    var modelData = {"Date":"\/Date(1338279675925)\/"};
    var jsDate = new Date(parseInt(modelData.Date.replace("/Date(", "").replace(")/",""), 10));
    alert(jsDate.toISOString());
</script>

Another possibility is to use Json.NET which allows you to serialize dates using ISO 8601 format instead of the built-in JavaScriptSerializer.

Sign up to request clarification or add additional context in comments.

6 Comments

But modelData also contains other properties, is it possible to use JQuery.each method perhaps?
I don't understand what does the fact that your modelData contains other properties has to do with dates serialization.
Thanks, I used your answer to solve it, also used JQuery.each() function: var modelData = @Html.Raw(data); And then: modelData = $.each(modelData, function(i, v) { var dateString = new Date(parseInt(v.Date.replace("/Date(", "").replace(")/",""), 10)); v.Date = dateString.getDate() + "/" + (dateString.getMonth() + 1) + "/" + dateString.getFullYear(); });
And you really should consider switching to JSON.NET. It's faster than JavaScriptSerializer and more powerful. And Scott Hanselman approves this message! ;) hanselman.com/blog/…
Completely agree with lucask. Json.NET will be the default serializer anyway in future ASP.NET MVC versions so why not start using it right now? This way you will have one less thing to worry about when you migrate your application.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.