Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Json.Encode() DateTime encoding issue string not date type

I am having an issue with the JavaScript that is produced by ASP.NET MVC's System.Web.Helpers.Json.Encode() if the model includes a DateTime property.

My Model:

public class MyViewModel
{
    public string MyString { get; set; }
    public DateTime MyDateTime { get; set; }
    public int MyInt { get; set; }
    public string[] MyStringArray { get; set; }
}

My Controller:

public ActionResult Index()
{
    var myViewModel = new MyViewModel();
    myViewModel.MyString = "My test string";
    myViewModel.MyInt = 100;
    myViewModel.MyDateTime = DateTime.Now;
    myViewModel.MyStringArray = new string[] { "string 1", "string 2" };

    return View(myViewModel);
}

My View:

<script type="text/javascript">

    var myViewModel = @Html.Raw(Json.Encode(Model)) ;

</script>

The Output:

<script type="text/javascript">

    var myViewModel = {"MyString":"My test string","MyDateTime":"\/Date(1372280916431)\/","MyInt":100,"MyStringArray":["string 1","string 2"]} ;

</script>

The issue is with the way the date is being encoded. It is a string and not a Date type.

I have also tried using Newtonsoft.Json.JsonConvert.SerializeObject() and I still get a string and not a Date type.

like image 693
Aaron Hoffman Avatar asked Jun 26 '13 22:06

Aaron Hoffman


2 Answers

Date type has no literals in JavaScript. You will have to call its constructor.

var myDate = new Date(@Html.Raw(Json.Encode(Model.MyDateTime)));
like image 66
Ufuk Hacıoğulları Avatar answered Sep 17 '22 19:09

Ufuk Hacıoğulları


Using Newtonsoft to encode the object results in an ISO formatted date.

@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))

Date Format:

0001-01-01T00:00:00
like image 26
TrueEddie Avatar answered Sep 16 '22 19:09

TrueEddie