0

I'm trying to pass an array from my MVC Model into a javascript array (to use in fullCalendar), however having an issue.

From the below, "myArray" is being populated with the correct amount of items from the model array, but when I try to show obj.DateTime (valid field within the MVC model array) it returns undefined. The undefined alert appears the correct amount of times for items in the array.

Any help at all would be appreciated.

var myArray = [];

@foreach (var d in Model.Appointments)
{
    @:myArray.push("@d");
}

myArray.forEach(function (obj) {
    alert(obj.DateTime);
})
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    What is this `@` syntax…? – deceze Aug 20 '18 at 11:37
  • razor syntax. is it incorrect? –  Aug 20 '18 at 12:05
  • I don't know. We just need to know *what it is*. Because it's neither [tag:javascript] nor [tag:model-view-controller]. – deceze Aug 20 '18 at 12:06
  • I saw it here: https://stackoverflow.com/questions/23781034/razor-mvc-populating-javascript-array-with-model-array –  Aug 20 '18 at 12:06
  • Please don't mix JavaScript and C# together. The code you have written is not correct. – Sahil Sharma Aug 20 '18 at 12:14
  • *DateTime* lives in the C#/Razor world, you try to mix things up (there's only *Date* in Javascript). I personnally would fetch the data via Ajax instead of building an ugly Array.push chain. – Rob Aug 20 '18 at 12:14
  • What kind of data that `Model.Appointments` and `obj.DateTime` has? If `Model.Appointments` is a `DateTime` array, you don't need `obj.DateTime` - use `new Date(obj)` instead. – Tetsuya Yamamoto Aug 21 '18 at 02:41

1 Answers1

0

You can't use @d for converting your C# object to java-script object directly. You should encode your C# object to make a json value.

This code will encode (Serialize) your C# object to a JSON model.

@Html.Raw(Json.Encode(d));

Here is another question like yours

Nima Boobard
  • 503
  • 2
  • 8
  • Thanks for your reply. Unfortunately I've been trying stuff like this to no avail. Can you give me more information on that? Model.Appointments is my array. Do you mean something like this? @foreach (var d in Model.Appointments) { @:myArray.push(@Html.Raw(Json.Encode(d))); } –  Aug 20 '18 at 12:46
  • Still gives me "undefined" for the correct amount if items in the array :( –  Aug 20 '18 at 12:49
  • Do you just have issue with `DateTime` property? You can solve your date converting problem with this post: https://stackoverflow.com/questions/27314663/asp-net-parse-datetime-result-from-ajax-call-to-javascript-date – Nima Boobard Aug 20 '18 at 17:46