0

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.

1
  • So arrayofdetails is the list of id's of the html <div> ? Commented Mar 25, 2014 at 12:26

2 Answers 2

3

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 '.

Sign up to request clarification or add additional context in comments.

7 Comments

Compilation Error: The name 'Json' does not exist in the current context
@GrahamHull, try it using the complete name: var jsonArray = '@Html.Raw(System.Web.Helpers.Json.Encode(arrayofdetails ))';;
@GrahamHull, please not that you must use a single quote ' and not double quotes " in order to make it work, i.e. var jsonArray = '@Html.Raw(Json.Encode(arrayofdetails ))';.
Newtonsoft.Json is referenced already, if i try the other way it says its not part of helper. Im using .net 4, don't know if that makes any difference.
@GrahamHull, please see my edit. There was an editing mistake regarding quotes and double quotes. If the helper is still not found, check if you have a reference to System.Web.Helpers and if not, add it to the project.
|
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.