Skip to content Skip to sidebar Skip to footer

Asp.net Mvc 3 Razor : Initialize A Javascript Array

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 repre

Solution 1:

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 = newArray();
activeArrays.push('7-21-2011');
activeArrays.push('7-22-2011');

or yet:

var activeDates = newArray();
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 = [ 
    newDate(2011, 6, 21, 0, 0, 0, 0), 
    newDate(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:

publicclassMyViewModel
{
    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
<scripttype="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(')/', '');  
    returnnewDate(parseInt(date));
});

Solution 2:

I just happen to do this yesterday and came up with this solution (if you want it to look like the output you have in your question - I was using this with jqplot):

<scripttype="text/javascript">var activeDates = ['@Html.Raw(string.Join("', '", @ActiveDates.Select(f => string.Format("{0:MM-dd-yyyy}", f)).ToArray()))']
</script>

Post a Comment for "Asp.net Mvc 3 Razor : Initialize A Javascript Array"