Accessing Viewbag list via Javascript

Asked

Viewed 258 times

0

I am trying to access the elements of a list stored in Viewbag as follows:

function equipamentoTemControle() {

   for(i = 0; i < @ViewBag.qtdEquipamentos; i++) {

      var contratocod = @ViewBag.DadosEquipamentos[i].contratocod;
   }

}

But when trying to access the attribute contratocod of the Indian i Visual Studio says that the variable i does not exist. How should I access ?

  • Shouldn’t be qtdEquipamentos[i].contratocod; instead of DadosEquipamentos[i].contratocod;?

  • No, because Viewbag.qtdEquipments is an integer, and Viewbag.Data Equipment is the list I want to access.

  • But the array is qtdEquipamentos right? in that case maybe qtdEquipamentos[i].DadosEquipamentos.contratocod?

  • No. qtdEquipments is only an integer. The array is Dataequipments

  • What gives alert(typeof @ViewBag.DadosEquipamentos);?

  • System.Collections.Generic.List`1[SCO.Models.Equipmentsmodel]

Show 1 more comment

1 answer

0

Solved.

var jsonObj = @Html.Raw(Json.Encode(ViewBag.DadosEquipamentos));

for(i = 0; i < jsonObj.length; i++) {

    var contratocod = jsonObj[i].contratocod;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.