Is it correct to use List with ViewModel?

1

I have ViewModel below:

 public class Crm_AnaliseViewModel
{
    public string TAG { get; set; }
    public int ATUALIZACAO { get; set; }
    public string RELATORIOS { get; set; }
}

Then in Controler did:

 public async Task<ActionResult> Index(Crm_AnaliseViewModel model)
    {
        if (Session["cod_cli"] != null)
        {
            if(model == null)
            {
                model = new Crm_AnaliseViewModel();
            }

            int cod_cli = Convert.ToInt32(Session["cod_cli"]);

            List<Crm_AnaliseViewModel> TAG_List = new List<Crm_AnaliseViewModel>();

            var query = (from s in db.Crm_Analise
                         where s.cliente_CRM.Equals(cod_cli)
                         group s by s.TAG into g
                         select new
                         {
                            TG = g.Key,
                            AT = g.Max(t => t.data_creat),
                            RL = g.Count()
                        });

            foreach(var item in query)
            {
                model.TAG = item.TG;
                model.RELATORIOS = item.AT;
                model.ATUALIZACAO = item.RL;
                TAG_List.Add(model);
            }

            return View(TAG_List);
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

Would it be correct, to use List to popular (if I may call it) a ViewModel ?

    
asked by anonymous 14.07.2017 / 23:27

1 answer

2

I do not see any problems in making a foreach to fill a ViewModel , the problem with your code is that you do not need to foreach , it's unnecessary, thus getting an example > :

public class Crm_AnaliseViewModel
{
    public string TAG { get; set; }
    public int ATUALIZACAO { get; set; }
    public DateTime RELATORIOS { get; set; }
}

public async Task<ActionResult> Index(Crm_AnaliseViewModel model)
{
    if (Session["cod_cli"] != null)
    {
        int cod_cli = Convert.ToInt32(Session["cod_cli"]);

        var query = (from s in db.Crm_Analise
                        where s.cliente_CRM.Equals(cod_cli)
                        group s by s.TAG into g
                    select new Crm_AnaliseViewModel
                    {
                        TAG = g.Key,
                        RELATORIOS = g.Max(t => t.data_creat),
                        ATUALIZACAO = g.Count()
                    })
                    .ToList();

        return View(query);
    }
    else
    {
        return RedirectToAction("Login", "Account");
    }
}
Note: I've removed some variables because the code does not need at least what's in the question.

    
15.07.2017 / 00:00