I am using umbraco 4. I want to loop through nodes and store its urlname in an array. So that array looks like … [‘aaa-node’,’bbb-node’,’ccc-node’]. But following code is not working…
<script type="text/javascript">
@{
var arr = new Array[10];
var j=0;
foreach (var node in Model.Children.Where("Visible"))
{
arr[j]=@node.UrlName;
j++;
}
}
</script>
But this gives Error loading Razor Script getnodes.cshtml
What is the mistake in code?
I’m guessing that you’re getting an index out of bounds exception since there could be more than 10 nodes.
I find it easier to debug razor code by wrapping it in a try catch and then outputting the error. Note that this really only works for runtime errors.
It’s a hard thing to wrap one’s mind around, I know. Razor code is evaluated server side and javascript is evaluated client side. So that means that there’s no real way for the two of them to work together.
What we’re doing with the line of code between the script tags is writing out the javascript that will be run by the browser after it downloads the rendered page. As far as razor is concerned, it’s just writing out a string in that spot. Even though parts of the languages look alike, razor doesn’t know anything about javascript. Json.Encode (razor) serializes your list object into json. Html.Raw (razor) makes sure the output is not encoded. (Remove that and view the source of the page in the browser to get an idea as to why that’s necessary.)