Reputation: 545
I am currently working on a ASP.Net MVC Razor application. in my controller, I load two dictionaries with data and place them in a ViewModel as follows:
public Dictionary<String, List<String>> EngineerSchedule { get; set; }
public Dictionary<String, List<String>> WeeklySchedule { get; set; }
when in the view, I traverse the dictionaries to retrieve the List objects at every Key, I then change this String List into an Array and send them to a JavaScript function.
In my Js function, I would like to assign the above array to JS variables, when doing so, the JS variables become an array where the index holds the entire array from the function call. Also, the params become an array of Chars
Any advice to why this happens will be greatly appreciated!
Code in View:
@foreach(var week in Model.WeeklySchedule)
{
var key = week.Key;
var values = week.Value.ToArray();
string[] eng = { };
foreach (var item in Model.EngineerSchedule)
{
if (item.Key == key)
{
eng = item.Value.ToArray();
}
}
@: gatherTimes('@Html.Raw(Json.Encode(key))', '@Html.Raw(Json.Encode(values))', '@Html.Raw(Json.Encode(eng))');
//In here, both values and engs are Array of the correct type and length
}
function gatherTimes(weekKey, values, engs)
{
var week =[];
var eng = [];
week[week.length] = values;
eng[eng.length] = engs;
for(var i = 0; i < engs.length; i++)
{
alert(engs[i]); //Outputs single chars, rather then the string values
alert(eng[i]); //Outputs an array with the length of all the chars from engs, but this array only has one value, which is the entire array from Engs
}
}
Upvotes: 1
Views: 154
Reputation: 797
As far as I can tell you are actually giving your javascript function strings as arguments since they are wrapped in quotes. Maybe there lies the confusion?
Upvotes: 0
Reputation: 415
One way to inject server side information into the JavaScript portion of your application is "stringifying" the .Net object and calling JSON.Parse on the client side.
If you have the Json.NET nuget package from Newtonsoft you can use the static method JsonConvert.SerializeObject()
to turn almost any C# data structure into a JSON string.
After you place that string of JSON into your view using the templating feature of the Razor view engine, you can store it to a variable like so:
var engineerString = @JsonConvert.SerializeObject(Model.EngineerSchedule);
var dictionary = JSON.parse(engineerString);
Upvotes: 1