Increase ViewBag in .cshtml

-1

I need to increment my ViewBag on my page .cshtml , for my PartialView in my Controller I initiate it: ViewBag.count = 0

In my page .cshtml I need to increase: example :

@{
for (int i = 0; i < 10; i++)
{
     ViewBag.count = i;
     Html.Partial("EditorTemplates/Endereco", Model.Enderecos[@i]);
}
}

My PartialView:

<div id="[email protected]"></div>

The following error occurs:

O índice estava fora do intervalo. Ele deve ser não-negativo e menor que o tamanho da coleção
    
asked by anonymous 22.12.2015 / 18:17

2 answers

0

I did it like this:

In my controller, I started my viewbag :

ViewBag.count = 0;

view:

@foreach (var telefone in Model.Telefones)
{
    @Html.Partial("Telefone", telefone)
}
    
22.12.2015 / 19:18
2

Business logic in View is a very bad practice, especially since ViewBag is an auxiliary object to transport Controller values to View .

If you really need variables in View , use normal .NET variables in your logic. If you need to pass data from a View to a PartialView , you should do it by ViewModels , not%

This excerpt can be perfectly spelled as follows:

@for (var enderecoObjeto in Model.Enderecos.Select((endereco, i) => new {endereco, i}))
{
     @Html.Partial("EditorTemplates/Endereco", enderecoObjeto);
}

Partial can have ViewBag or you can type the object with @model dynamic using ViewModel .

    
22.12.2015 / 18:49