How to call Linq method in View?

Asked

Viewed 90 times

2

Good morning, everyone. my question is this, I have the following method in my model:

public IQueryable GetConsulta()
{
    var q = (from c in Datacontext.Tabela1
                join b in Datacontext.Tabela2 on c.CodClase equals b.CodClase
                join d in Datacontext.Tabela3 on b.CodImobilizado equals d.CodImobilizado
                where c.CodClase == b.CodClase && b.CodImobilizado == d.CodImobilizado
                select new
                {
                    taxa = c.Taxa,
                    ano = DateTime.Parse(b.Data).Year,
                    data = d.Data,
                    valorAquisicao = b.Valor,

                });

    return q;
}

In View it’s like this:

void getConsulta(){
    var a = model.GetConsulta();    
    foreach(var linha in a){
      //faça algo
    }
}

The problem is that I cannot access the variables created in the model method in the View foreach.

Could someone help me.

  • You’re returning this to the View?

  • yes Marconi. i need to access the result of the select made in the model, within the foreach cycle that appears in the getquery method that is found in Viewer

  • And the answer below, I think it helps you. :)

1 answer

2


The problem is in the type of return you are using, in this approach, you do not specify which return of Iqueryable, consequently in the view, you will not be able to view the desired data.

A suggestion would be to type your return with a model class:

class Modelo {
    public string taxa { get; set; }
    public int ano { get; set; }
    public DateTime data { get; set; }
    public decimal valorAquisicao { get; set; }
}

public IQueryable<Modelo> GetConsulta()
{
    var q = (from c in Datacontext.Tabela1
                join b in Datacontext.Tabela2 on c.CodClase equals b.CodClase
                join d in Datacontext.Tabela3 on b.CodImobilizado equals d.CodImobilizado
                where c.CodClase == b.CodClase && b.CodImobilizado == d.CodImobilizado
                select new Modelo()
                {
                    taxa = c.Taxa,
                    ano = DateTime.Parse(b.Data).Year,
                    data = d.Data,
                    valorAquisicao = b.Valor,

                });

    return q;
}

In View it would look like this:

void getConsulta(){
    var a = model.GetConsulta();    
    foreach(Modelo linha in a){
      //faça algo
    }
}
  • That may be it, well remembered. :)

  • This is probably the situation. In this case my variable q would have to be the right model type?

  • Yes, I’ll edit the answer

  • Thanks so much Julio. your reply was very helpful Thanks Even. Note: I am new to this forum. where can I mark as valid reply?

  • Below the vote marker has a V, just click on it to mark the answer as valid.

Browser other questions tagged

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