Problem generating list in a ViewModel

1

I'm working on ASP.Net with MVC 4 , and when doing a search / using filters I'll present a resulting list of data. To better handle this result I created a ViewModel where I put information from several tables. Now to populate the list I'm doing the following:

I create a variable of data type of ViewModel :

var resultFiltro = new FiltroSPlaneamentoViewModel();

And I create a list of the same data type:

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

Problem: When you go through a foreach to enter the data in the list, and adding the resultFiltro variable in the same list, all other data in the list changes and becomes equal to resultFilto .

Example of a foreach I'm using:

//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);
            }
    
asked by anonymous 14.02.2014 / 10:54

1 answer

1

I've already figured out what the problem is: In every cycle of foreach I have to put resultFiltro to point 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);
            }
    
14.02.2014 / 11:17