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.
replacer
callback to handle stringification:JSON.stringify(value[, replacer[, space]])
), you can embed these members properly. JSON.NET can then interpret and revive objects with strong types, as long as those types exist on the server-side. You can implement your own type-mapping scheme (I've done intermediate types, template types, namespace mirroring, etc.), built into JSON.NET. It's easier in AS3 due to strong types, unlike JavaScript. – Damnable