4

I am currently working on an ASP.Net MVC application. From my database, I have created three dictionaries and stored them inside a View Model.

After populating said dictionaries with some logic in the controller, I'm accessing these dictionaries in my View via @Model

After manipulating these dictionaries, I need to send the data to a JS function to apply some logic to a JS library called DHtmlxScheduler

I have read about the Razor syntax using @: and am currently using this method to send two string arrays. when trying to access these arrays in the JS function, they only appear to hold System.String[]

Here is the code:

var weekArray;
var engArray;

@foreach(var week in Model.WeeklySchedule)
{
    var key = week.Key;
    var values = week.Value.ToArray();
    var eng = Model.EngineerSchedule.Where(k => k.Key == key).Select(v => v.Value).ToArray();
    string test = "hello";

    @: gatherTimes('@values', '@eng');
}

function gatherTimes(values, engs)
{
    for(var i = 0; i < values.length; i++)
    {
        alert(values[i]);
    }

    //alert(values);
    //alert(engs);

    //weekArray[weekArray.length] = values;
    //engArray[engArray.length] = engineers;
}

I eventually plan on looping through the arrays, they hold information about time slots and engineer IDs. If there is any more information I may provide, I will do my best to do so.

2

1 Answer 1

3

You will need to encode the list to JSON using JSON.Encode. Here is an example:

@{    
   // C# collection
   var collection= new List<string> {"A", "B", "C"};
 }

<script type="text/javascript"> 
   // encode C# collection to JSON, set to javascript variable
   var arr = @Html.Raw(Json.Encode(collection))
   for(var i = 0; i < arr.length; i++)
   {
      console.log(arr[i]); // Output is A  B  C
   }
</script>

In your case it would be like so:

@: gatherTimes('@Html.Raw(Json.Encode(values))', '@Html.Raw(Json.Encode(eng))');    
Sign up to request clarification or add additional context in comments.

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.