Is it correct to use List with Viewmodel?

Asked

Viewed 272 times

2

I own the ViewModel down below:

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

Then in the Controler done:

 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");
        }
    }

It would be right to use List to popular (if I may call it) a ViewModel?

  • Your code doesn’t need to make a foreach can be summed up in another way! has no problem filling a foreach the problem I’m seeing is in your code now!

1 answer

2


I see no problem making one foreach to fill a ViewModel, the problem with your code is you don’t have to do this foreach, is unnecessary, thus leaving a 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");
    }
}

Observing: I’ve removed some variables because the code doesn’t need, at least what’s in the question.

Browser other questions tagged

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