Problem generating list in Viewmodel

Asked

Viewed 352 times

1

I’m working on ASP.Net with MVC 4, and when doing a search/use filters I will present a list of resulting data. To better manipulate this result I created a ViewModel where I put information from various tables. Now to fill the list I am doing the following:

I create a variable of the data type of the ViewModel:

var resultFiltro = new FiltroSPlaneamentoViewModel();

And I create a list of the same kind of data:

 List<FiltroSPlaneamentoViewModel> listaResultFiltro = new List<FiltroSPlaneamentoViewModel>();

Problem: While walking a foreach to enter the data in the list, and adding the variable resultFiltro in the same list, all other data in the list are changed and are equal to resultFilto.

Example of a foreach that I’m wearing:

//Pesquisar Técnico Responsável
            var serv = db.Servicos.Where(s => s.NumTransportado == TecnicoResp).ToList();
            foreach (var item in serv)
            {
                resultFiltro.idFiltro += 1;
                resultFiltro.Serie = item.DadosComerciais.Serie;
                resultFiltro.NumDoc = item.DadosComerciais.NumDoc;
                resultFiltro.ServicoID = item.ServicosID;
                resultFiltro.TecnicoResponsavel = item.NumTransportado;
                listaResultFiltro.Add(resultFiltro);
            }

1 answer

1


I’ve already found the problem: In every cycle of foreach I have to put resultFiltro pointing to a new element. Staying:

foreach (var item in forn)
            {
                resultFiltro = new FiltroSPlaneamentoViewModel(); //FALTAVA apontar para novo elemento
                resultFiltro.idFiltro += 1;
                resultFiltro.Serie = item.Serie;
                resultFiltro.NumDoc = item.NumDoc;
                resultFiltro.NumFornecedor = item.IdFornecedor;
                listaResultFiltro.Add(resultFiltro);
            }
  • An hour looking for a mistake like this :/

  • Very well Cesar. You can mark your answer as right, so that the question is not pending.

Browser other questions tagged

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