1

I'm iterating through my Model in javascript and I get a compilation error : " The name 'i' does not exist in the current context" alerting i is working ok. How can I escape the Razor to get the i please ?

for(i=0; i<@Model.Count();i++)
{
    //alert(i);
    alert(@Model.ElementAt(i).Description.ToString());
}

3 Answers 3

3

You are mixing javascript and Razor. Try only using javascript for the alert call.

@for(var i=0; i<@Model.Count(); i++)
{
    <text>
    alert("@Model.ElementAt(i).Description.ToString()");
    </text>
}
Sign up to request clarification or add additional context in comments.

Comments

2

@model is something the server knows, and the value of 'i' is something the client knows. You would either need to recreate the array as a javascript array and use that instead of @model, or maybe use ajax instead and pass the value of i as a parameter

Comments

0

It looks like the problem is that you just forgot to declare i in the for loop and properly declare it as C# syntax

@for(var i = 0; i < @Model.Count(); i++) {
  ...
}

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.