Reputation: 39068
I'm assigning a list to the view bag like so:
ViewBag.MyArray = GetSomeIEnumerable();
On the client, I render the page and can access the elements from JS executed in onload by fix strings like so:
$(document).ready(function () {
var output = "Info: @(ViewBag.MyArray["honka"]["ponka"])";
alert(output);
}
However, I'm not clear on how to access the element if the indexes are specified as variables like so:
$(document).ready(function () {
var honka = "honka";
var ponka = "ponka";
var output = "Info: @(ViewBag.MyArray[???][???])";
alert(output);
}
I've tried escaping by backslash-quote, using it straight of and a few other variants but apparently I'm not getting the syntax right as I get errors like variable not recognized in scope and missing closing parantesis.
<td>
@(ViewBag.MyArray[a][b])
</td>
I also added the using keyword at the top of both CS and CSHTML file.
@{
Layout = null;
}
@using TestService.ServiceReference;
@using System.Web.Helpers;
<!DOCTYPE html>
<html>
...
Upvotes: 0
Views: 1616
Reputation: 4290
This can't be done as the @(ViewBag.MyArray["honka"]["ponka"])
expression is evaluated on the server and then replaced by the value before it is sent to the client and the javascript is executed.
The issue is that the server needs to know these variables before rendering the page.
Pass these variables to the server via the url's querystring.
Example razor syntax
// url : ../?var1=honka&var2=ponka
$(document).ready(function () {
var output = 'Info: @(ViewBag.MyArray[Request["var1"]][Request["var2"])';
alert(output);
}
Assign the whole ViewBag.MyArray as Json to a JavasCript variable.
Example razor syntax
$(document).ready(function () {
var honka = "honka";
var ponka = "ponka";
var myArray = @Html.Raw(Json.Encode(ViewBag.MyArray));
var output = "Info: " + myArray[honka][ponka];
alert(output);
}
Upvotes: 1