GrahamHull
GrahamHull

Reputation: 325

Access an 'mvc' array in javascript

Heres the following problem im generating an array in C# MVC view and trying to access it in a javascript function.

string[] arrayofdetails = new string[count];

it contains a list of divs that i want hiding

   <script type="text/javascript">
    for(int x = 0;x < @count; x++)
    {
        $('#@arrayofdetails[x]').hide();
    } 
    </script>

I dont even know if this is possible or if im way off base, javascript newbie.

thanks.

Upvotes: 0

Views: 729

Answers (2)

Andrei V
Andrei V

Reputation: 7496

You can't interact in that way with C# and JavaScript. I would suggest the following: convert the C# array into a JSON string and assign it to a JavaScript variable; inside your <script> parse the array into a valid object:

<script type="text/javascript">
    //for debugging purpose use two lines
    var jsonArray = '@Html.Raw(Json.Encode(arrayofdetails ))';
    var arryObj = JSON.parse(jsonArray);

    //alternatively, call "JSON.parse()" directly  
    //var arryObj = JSON.parse('@Html.Raw(Json.Encode(arrayofdetails ))');

    for(int x = 0; x < arryObj.length ; x++)
    {
        $('#' + arryObj[x]).hide();
    } 
</script>

NOTE: Since the Json.Encode method produces a JSON string, the values of the properties/arrays will almost always be double quoted (e.g. "myValue"). Constructs such as var jsonString = "{ myProperty: "myValue" }"; are illegal in JavaScript. Therefore, the generated JSON string must be wrapped inside single quotes '.

Upvotes: 3

Kunukn
Kunukn

Reputation: 2236

If you need to mix Razor with Javascript

@{
    var arrayofdetails = new []{"one","two","three"};    
}
<div id="content"></div>
<script>
    @foreach (var s in arrayofdetails)
    {                        
        @: console.log('@s');            
        @: document.getElementById("content").innerHTML += '@s <br/>';
    }    
</script>

Upvotes: 0

Related Questions