Increment Viewbag in . cshtml

Asked

Viewed 88 times

-1

I need to step up my ViewBag on my page .cshtml, to my PartialView in my Controller I start her off: ViewBag.count = 0

On my page .cshtml need to increase: example:

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

mine PartialView:

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

following error occurs:

O índice estava fora do intervalo. Ele deve ser não-negativo e menor que o tamanho da coleção
  • 1

    I guess I’d have to put @ before FOR... SOMETHING LIKE @{ for(int i = 0; i < 10; i++){ Viewbag.Count = i } }

  • @Paulohdsousa I will implement more the question, thank you for answering

  • worked what I said? @Furlan

  • @Paulohdsousa another error occurred

  • So, it turns out that within Model.Addresses[] the amount of elements is smaller than being passed in I, Another point... Pass like this -> Model.Addresses[i]);

  • 4

    uses foreach my dear!

  • 1

    I find it much better adica from @Rboschini

  • @How would Rboschini be wearing foreach ?

Show 3 more comments

2 answers

2

Business logic in View is a lousy practice, especially because ViewBag is an auxiliary object to carry values from Controller to the View.

If you really need variables in View, use normal . NET variables in your logic. If you need to pass data from a View for a Partialview, must do for Viewmodels, and not by ViewBag.

This excerpt can be perfectly written as follows:

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

To Partial may have @model dynamic or you can type the object with the i using Viewmodel.

  • Dude, can I propose codes like this to the guys who ask? I usually concert code errors even when it could be made 100x better, I can do it then right? @Cigano Morrison Mendez

  • 1

    You can even fix it, but the code is bad even in its formulation. There’s not much to do.

  • 1

    I’m kind of into changing someone else’s code, but thanks for the info. @Cigano Morrison Mendez

0


I managed to do so:

on my controller, I started my viewbag:

ViewBag.count = 0;

in the view:

@foreach (var telefone in Model.Telefones)
{
    @Html.Partial("Telefone", telefone)
}
  • Edit your question with this data, do not post an answer.

  • 1

    @Rboschini By the incredible that it seems, this is really the answer to his problem.

Browser other questions tagged

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