Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  123] [ 4]  / answers: 1 / hits: 24019  / 13 Years ago, thu, july 21, 2011, 12:00:00

What would be the prefered way to initialize a JS array in ASP.NET MVC 3 with Razor with a value I have in my model/view model ?



For example to initialize an array of strings representing dates :



<script type=text/javascript>
var activeDates = [7-21-2011, 7-22-2011];
</script>


with



public class MyViewModel
{
public DateTime[] ActiveDates { get; set; }
}

More From » arrays

 Answers
359

I don't quite understand the relation between JS and ASP.NET MVC 3 Razor. Javascript runs on the client side no matter which technology has been used on the server to generate the page. So on javascript an array is an array.



There are a couple of possibilities to define arrays of objects in javascript



var activeDates = [ '7-21-2011', '7-22-2011' ];


or:



var activeDates = new Array();
activeArrays.push('7-21-2011');
activeArrays.push('7-22-2011');


or yet:



var activeDates = new Array();
activeArrays[0] = '7-21-2011';
activeArrays[1] = '7-22-2011';


At th end all those represent the same array. But it is an array of strings, not dates.



If you wanted to have an array of dates, here's what you could do:



var activeDates = [ 
new Date(2011, 6, 21, 0, 0, 0, 0),
new Date(2011, 6, 22, 0, 0, 0, 0)
];


Now the only relation I can see with your question to ASP.NET MVC is that you probably have some array on your view model:



public class MyViewModel
{
public DateTime[] ActiveDates { get; set; }
}


that you wanted to serialize and manipulate in a javascript array. In this case here's the syntax:



@model MyViewModel
<script type=text/javascript>
var activeDates = @Html.Raw(Json.Encode(Model.ActiveDates));
</script>


Now because of the way DateTime fields are JSON serialized in .NET you will end up with the following in the generated HTML:



var activeDates = [/Date(1309471200000)/,/Date(1311199200000)/];


and if you wanted to convert this array of strings into an array of actual javascript dates:



var dates = $.map(activeDates, function(date, index) {
date = date.replace('/Date(', '').replace(')/', '');
return new Date(parseInt(date));
});

[#91079] Wednesday, July 20, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eliasf

Total Points: 703
Total Questions: 97
Total Answers: 129

Location: Chad
Member since Tue, Apr 27, 2021
3 Years ago
;