Reputation: 761
I am pulling a list of data from the web and placing my array into my drop down menu. I am using razor script and I get the following error on LINE 4:
The name 'i' does not exist in this current context
Here is my code:
var select = document.getElementById('propertyMenu');
for (var i = 0; i < @Model.propertiesArray.Length; i++)
{
var property = "@Model.propertiesArray[i]"
var element = document.createElement('option');
element.textContent = property;
element.value = property;
}
Now I know that using the '@' symbol allows you to access classes from my models within my javascript via C#. So my guess is that the Javascript variable 'i' won't be accessible unless I give it some sort of directive.
How do I access my int count 'i' within the context?
EDIT:
I answered my own question.
Upvotes: 0
Views: 576
Reputation: 761
var propertiesArray = new Array();
@foreach (var props in Model.propertiesArray)
{
@:propertiesArray.push("@props");
}
var select = document.getElementById("propertyMenu");
for (var i = 0; i < propertiesArray.length; i++)
{
var property = propertiesArray[i];
var element = document.createElement('option');
element.textContent = property;
element.value = property;
select.appendChild(element);
}
Upvotes: 1
Reputation:
because you are using in Javascript codes. You can try this.
@{
string values = "";
for(int i=0;i<Model.propertiesArray.Length;i++)
values += Model.propertiesArray[i].ToString()+(i!=Model.propertiesArray.Lenght-1)?",":"";
}
<script>
var value = '@values';
var values = value.split(',');
var select = document.getElementById('propertyMenu');
for (var i = 0; i < values .length; i++)
{
var property = values[i];
var element = document.createElement('option');
element.textContent = property;
element.value = property;
}
</script>
I wrote Stackoverflow editor.
Upvotes: 0
Reputation: 5156
can not tell if your code is C# or JS.
You may have to do it this way
var select = document.getElementById('propertyMenu');
for (var i = 0; i < @Model.propertiesArray.Length; i++)
{
var property = @Model.propertiesArray[i].toString();
var element = document.createElement('option');
element.textContent = property;
element.value = property;
}
Upvotes: 0