ASP.NET MVC 3 Razor : Initialize a JavaScript array

23,508

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 = 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));
});

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):

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

Matthieu

Learning. When done, learn more.

Updated on July 09, 2022

Comments

  • Matthieu
    Matthieu almost 2 years

    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; }
    }
    
  • Matthieu
    Matthieu almost 13 years
    Adjusted my question to have a better description of the issue, thanks !
  • TheCloudlessSky
    TheCloudlessSky almost 13 years
    +1 - You can even shorten the map function to use new Date(parseInt(date.substr(6))); since parseInt will ignore the ending )/.
  • Matthieu
    Matthieu almost 13 years
    "@string" shouldn't be "@Html.Raw(String" with according ) at the end and "@ActiveDates", Model.ActiveDates ? Or is it a difference between C# Razor and VB razor ?
  • Buildstarted
    Buildstarted almost 13 years
    In this case you're right because Razor will encode the ''s I just wrote it off the cuff but thanks for that. :)
  • awe
    awe about 12 years
    @Matthieu: Lowercase s on string is valid for C#. There is nothing in your question that dictates VB, so this answer is valid enough. I'm not sure how VB will handle a lowercase s here. VB use uppercase S, but in the past it has never been to picky about casing on types. I don't know how it is in VB Razor, as I have only recently started using MVC/Razor, and only coded in C# Razor. As a side note, you would always get it right using uppercase on String, because this is how the .NET version of it is declared (regardless of language).
  • Lakshay Dulani
    Lakshay Dulani about 10 years
    @DarinDimitrov We are not mixing C# and JS here. We are just trying to render a statement through razor C# which the JS compiler can take and initialize an array.
  • Darin Dimitrov
    Darin Dimitrov about 10 years
    @Lakshay, I didn't say the contrary.