How to add items from a IENUMERABLE in . Net MVC into a Jquery array?

Asked

Viewed 314 times

2

How do I add items from a IEnumerable<T> in an array JavaScript?

View:

@using Colecao.ViewModels
@model ConfiguracoesViewModel

    @foreach (var equipamento in @Model.Equipamentos)
    { 
              //Gostaria de adicionar esses itens em um array JS.
    }
  • In Javascript there is no IEnumerable...

  • 1

    You’re confused to understand. You want to pass one IEnumerable an Action for your JS? Or IEnumerable is on your JS?

  • I pass the Ienumerable to the view! and in the JS I would like to manipulate the items of Ienumerable ,adding in an array .

  • @Hansmiller how are you going to view? you can put the code or how it appears in the view?

  • 1

    I get it, do you have any code made? This can help to better understand what you have and the staff help you in the best way. If so, click on [Edit] and add these details.

1 answer

2

You can do it this way:

var equipamentos = @Html.Raw(Json.Encode(Model.Equipamentos));

How to use?

You can use normally as if it were any json.

Let’s say my equipment model is like this:

public class Equipamentos
{
    public string Nome { get; set;}
    public string Modelo { get; set;}
}

Its use shall be as follows::

alert("Nome: "+ equipamentos[1].Nome + " | Modelo: "+ equipamentos[1].Modelo);
  • How can I manipulate this variable within my JS function?

  • Like any array, only the properties will depend on your model.

  • @Hansmiller, I’ll edit the question by adding how to use

  • Blz! just one question where do I put this function? var [email protected](Json.Encode(Model.Equipments));

  • @Hansmiller, put it inside your tag <script></script>.

  • what would foreach look like in Jquery to add to Array?

  • @Hansmiller, move the model to an array or move json model for an array??

  • var equipamentos = @Html.Raw(Json.Encode(Model.Equipment); how to move each item within the equipment collection to an array[].

  • @Hansmiller, equipment is already an array. An array of equipment. If you want to redo the list, you can do $.each(dispositivos,function(key, value){ console.log(key + " | " + value.Nome + " - " + value.Numero );});

Show 4 more comments

Browser other questions tagged

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