IT ppl
IT ppl

Reputation: 2647

Error in adding element to array on view + MVC

Timeline.js + MVC + JavaScript

I am having the following code on my view

@{           
    var objs = objstudent.Timelines.Where(x => x.StudentID == Sessions.objStudent.StudentID).AsQueryable();
}
<script type="text/javascript">
@{
    @:var data = [];
    foreach(Student.Models.Timeline student in objs)
    {
         @:data.push({start : new Date "@student.MeetingDate", content : "@student.Description" });
    }
}

here I am trying to add details in data array which will be used for displaying details in timeline, but when I check data's value in browser it shows me undefined.

I have tried using but problem is same.

any solution ?

Upvotes: 0

Views: 339

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Never build javascript literals manually like this. Always use proper serializers. For example:

@{           
    var objs = objstudent.Timelines.Where(x => x.StudentID == Sessions.objStudent.StudentID).AsQueryable();
}
<script type="text/javascript">
    var data = @Html.Raw(
        Json.Encode(
            objs.Select(x => new 
            { 
                start = x.MeetingDate, 
                content = x.Description 
            })
        )
    );
</script>

should end up with something along the lines of:

<script type="text/javascript">
    var data = [
        { "start": "\/Date(1334655137358)\/", "content": "foo" },
        { "start": "\/Date(1334655137358)\/", "content": "bar" },
        ...
    ];
</script>

Notice that the DateTime fields are serialized using the /Date(Ticks) format. You could use various techniques to convert them to native javascript dates.

Upvotes: 1

Related Questions