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.
Date type has no literals in JavaScript. You will have to call its constructor.
var myDate = new Date(@Html.Raw(Json.Encode(Model.MyDateTime)));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With